how to reqeust additional file info in client side? - httprequest

Can i add some file info in client side, and receive these info and files in serverside in one request?
The code below is what i've tried.
I hope to send fileName(string) and fileSize(string) info which are from the client side request to the server
This is client side UI
Client side request
// console.log(files)
(2) [File, File]
0: File
fileName: "home banner"
fileSize: "md"
lastModified: 1578046598141
lastModifiedDate: Fri Jan 03 2020 19:16:38 GMT+0900 (Korean Standard Time) {}
name: "주석 2020-01-03 191634.png"
size: 80587
type: "image/png"
webkitRelativePath: ""
__proto__: File
1: File
fileName: "home carousel"
fileSize: "sm"
lastModified: 1585672500304
lastModifiedDate: Wed Apr 01 2020 01:35:00 GMT+0900 (Korean Standard Time) {}
name: "Capture001.png"
size: 756604
type: "image/png"
webkitRelativePath: ""
__proto__: File
length: 2
// on submit
const handleSubmit = (e) => {
e.preventDefault();
console.log(files);
const formData = new FormData();
files.forEach((file, i) => formData.append('file' + i, file));
fetch('/image/upload', {
method: 'POST',
body: formData,
});
};
Server side
app.post('/image/upload', (req, res) => {
console.log(req.files);
});
// log
{
file0: {
name: '주석 2020-01-03 191634.png',
data: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 06 45 00 00 03 0f 08 06 00 00 00 6b 13 d2 fd 00 00 00 01 73 52 47 42 00 ae ce 1c e9 00 00 00 04 ... 80537 more bytes>,
size: 80587,
encoding: '7bit',
tempFilePath: '',
truncated: false,
mimetype: 'image/png',
md5: '5dc5122f8334ba14b362f4dcf96cd729',
mv: [Function: mv]
},
file1: {
name: 'Capture001.png',
data: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 0a 00 00 00 08 70 08 06 00 00 00 e1 e9 67 30 00 00 00 01 73 52 47 42 00 ae ce 1c e9 00 00 00 04 ... 756554 more bytes>,
size: 756604,
encoding: '7bit',
tempFilePath: '',
truncated: false,
mimetype: 'image/png',
md5: '3858e650b34e3210d41e923f249e9018',
mv: [Function: mv]
}
}

Adding fields to the File object will not add it to the upload, you're going to have to upload that data separately.
const handleSubmit = (e) => {
e.preventDefault();
console.log(files);
const formData = new FormData();
files.forEach((file, i) => {
formData.append('file' + i, file);
formData.append('file' + i + 'fileName', file.fileName);
formData.append('file' + i + 'fileSize', file.fileSize);
});
fetch('/image/upload', {
method: 'POST',
body: formData,
});
};
On the server
app.post('/image/upload', (req, res) => {
console.log(req.files);
console.log(req.body);
});
Log
{
file0fileName: "home banner",
file0fileSize: "md",
file1fileName: "home carousel",
file1fileSize: "sm",
}

Related

WifiManager.connectToProtectedSSID - most likely the callback was already invoked

I got this error when trying to use react-native-wifi-reborn to connect with with
Invariant Violation: No callback found with cbID 2567 and callID 1283 for WifiManager.connectToProtectedSSID - most likely the callback was already invoked. Args: '[{"code":"unableToConnect","message":"internal error.","domain":"NEHotspotConfigurationErrorDomain","userInfo":{"NSLocalizedDescription":"internal error."},"nativeStackIOS":["0 wifiborn 0x0000000100f47024 RCTJSErrorFromCodeMessageAndNSError + 120","1 wifiborn 0x0000000100eddad4 __41-[RCTModuleMethod processMethodSignat...(truncated)...","2 wifiborn 0x0000000100e3c55c __77-[WifiManager connectToProtectedSSID:...(truncated)...","3 NetworkExtension 0x00000001ad1427ac 9AAC742E-D5F7-3619-BC05-EA4F2D8601FB + 505772","4 libdispatch.dylib 0x0000000103f18064 _dispatch_call_block_and_release + 32","5 libdispatch.dylib 0x0000000103f19d90 _dispatch_client_callout + 20","6 libdispatch.dylib 0x0000000103f2a058 _dispatch_main_queue_callback_4CF + 1040","7 CoreFoundation 0x000000019bb581f8 58500388-BF36-397C-84CF-17315A3445B6 + 668152","8 CoreFoundation 0x000000019bb520d0 58500388-BF36-397C-84CF-17315A3445B6 + 643280","9 CoreFoundation 0x000000019bb511c0 CFRunLoopRunSpecific + 600","10 GraphicsServices 0x00000001b3139734 GSEventRunModal + 164","11 UIKitCore 0x000000019e5bf7e4 186C18FD-1082-3811-A761-88E8376C7E69 + 12363748","12 UIKitCore 0x000000019e5c5054 UIApplicationMain + 168","13 wifiborn 0x0000000100975950 main + 120","14 libdyld.dylib 0x000000019b80dcf8 B08AB7C2-64E8-3937-9487-C33D0175FD34 + 7416"]}]'
Simply using this function:
const connectWithWifi = async () => {
try {
//initWifi();
const data = await WifiManager.connectToProtectedSSID(
ssid,
password,
false,
);
console.log('Connected successfully!', {data});
setConnected({connected: true, ssid});
} catch (error) {
setConnected({connected: false, error: error.message});
console.log('Connection failed!', {error});
}
};
someone can Help me?

API calling doesn't response in JSON and instead responses in some nonsense Data

I'm trying to call an API in Go, and like below I declare my method and other things in order to get the response I require but the problem I'm facing is I don't know if I have a problem in my request or the response it return have a problem.
This is the function that I use too pass data and call API
func APICall(url string,method string,request string) []byte{
payload := strings.NewReader(request)
client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Access", "application/json")
res, err := client.Do(req)
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
return body
}
func Search(c *gin.Context) {
url := "https://testapi-v3.iati.ir/Tools/Ping/*************"
method := "POST"
payload := "{\"Echo\":\"asd\"}"
resAsByte := APICall(url,method,payload)
fmt.Println(resAsByte)
var v map[string]interface{}
err := json.Unmarshal(resAsByte,&v)
fmt.Println(err)
}
by the way
err := json.Unmarshal(resAsByte,&v)
doesn't work and this is the binary response that I got
[171 86 114 77 206 200 87 178 82 74 44 78 81 210 81 242 12 112 76 73 41 74 45 46 6 138 152 152 233 25 153 152 234 25 155 235 25 26 27 43 213 2 0]
Your APICall returns []byte. So here you see a representation of []byte.
You may convert []byte to string:
var s = string(body)
Then print s and see a string.

App rejected: React Native app crashed when opening image crop picker

No issues or crashes with app on build mode and in 3 different devices.
App got rejected by App Store review.
Rejection reason: The app crashed when we selected the image uploader.
Now I'm need guidance trying to figure out what the cause of the crash is because I can't recreate it. And before considering using another image picker package I would like to try to make sense of this crash first.
Additional Information
"react-native": "0.57.1",
"react-native-image-crop-picker": "^0.21.3",
"rn-fetch-blob": "^0.10.14"
Library used: https://github.com/ivpusic/react-native-image-crop-picker
Code used (Is anything missing?):
openPhotoPicker() {
const { currentUser } = firebase.auth()
const Blob = RNFetchBlob.polyfill.Blob
const fs = RNFetchBlob.fs
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob
ImagePicker.openPicker({
width: 60,
height: 60,
compressImageMaxWidth: 800,
compressImageMaxHeight: 800,
compressImageQuality: 0.8,
cropping: true,
smartAlbums: ['UserLibrary', 'Favorites'],
mediaType: 'photo'
}).then(image => {
const imagePath = image.path
let uploadBlob = null
const imageRef = firebase.storage()
.ref(`/users/${currentUser.uid}/progress`)
.child(`${toJSONLocal(this.state.newDate)}.jpg`)
let mime = 'image/jpg'
fs.readFile(imagePath, 'base64')
.then((data) => {
return Blob.build(data, { type: `${mime};BASE64` })
})
.then((blob) => {
uploadBlob = blob
return imageRef.put(blob, { contentType: mime })
})
.then(() => {
uploadBlob.close()
return imageRef.getDownloadURL()
})
.then((url) => {
let obj = {}
obj["progressPhoto"] = url
this.setState(obj)
this.addPhotoDatabase() // Photo uploaded to firebase storage is also uploaded to database so it can be referenced.
})
.catch((error) => {
console.log(error);
})
})
.catch((error) => {
console.log(error);
});
}
Here's the symbolicated crash report:
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note: EXC_CORPSE_NOTIFY
Triggered by Thread: 1
Application Specific Information:
abort() called
Last Exception Backtrace:
0 CoreFoundation 0x1b64cf518 __exceptionPreprocess + 228
1 libobjc.A.dylib 0x1b56aa9f8 objc_exception_throw + 55
2 MyApp 0x10048a3f8 RCTFatal + 222200 (RCTAssert.m:132)
3 MyApp 0x100486938 -[RCTExceptionsManager reportFatalException:stack:exceptionId:] + 207160 (RCTExceptionsManager.m:58)
4 CoreFoundation 0x1b64d6ba0 __invoking___ + 143
5 CoreFoundation 0x1b63b8c90 -[NSInvocation invoke] + 291
6 CoreFoundation 0x1b63b98c4 -[NSInvocation invokeWithTarget:] + 59
7 MyApp 0x10049eaa0 -[RCTModuleMethod invokeWithBridge:module:arguments:] + 305824 (RCTModuleMethod.mm:550)
8 MyApp 0x1004e5750 facebook::react::invokeInner(RCTBridge*, RCTModuleData*, unsigned int, folly::dynamic const&) + 595792 (RCTNativeModule.mm:104)
9 MyApp 0x1004e54ac invocation function for block in facebook::react::RCTNativeModule::invoke(unsigned int, folly::dynamic&&, int) + 595116 (RCTNativeModule.mm:71)
10 libdispatch.dylib 0x1b5f0fa38 _dispatch_call_block_and_release + 23
11 libdispatch.dylib 0x1b5f107d4 _dispatch_client_callout + 15
12 libdispatch.dylib 0x1b5eb9320 _dispatch_lane_serial_drain$VARIANT$mp + 591
13 libdispatch.dylib 0x1b5eb9e3c _dispatch_lane_invoke$VARIANT$mp + 427
14 libdispatch.dylib 0x1b5ec24a8 _dispatch_workloop_worker_thread + 595
15 libsystem_pthread.dylib 0x1b60f0114 _pthread_wqthread + 303
16 libsystem_pthread.dylib 0x1b60f2cd4 start_wqthread + 3
Thread 1 name: Dispatch queue: com.facebook.react.ExceptionsManagerQueue
Thread 1 Crashed:
0 libsystem_kernel.dylib 0x00000001b606d0dc __pthread_kill + 8
1 libsystem_pthread.dylib 0x00000001b60e6094 pthread_kill$VARIANT$mp + 380
2 libsystem_c.dylib 0x00000001b5fc6ea8 abort + 140
3 libc++abi.dylib 0x00000001b5693788 __cxa_bad_cast + 0
4 libc++abi.dylib 0x00000001b5693934 default_unexpected_handler+ 6452 () + 0
5 libobjc.A.dylib 0x00000001b56aae00 _objc_terminate+ 24064 () + 124
6 libc++abi.dylib 0x00000001b569f838 std::__terminate(void (*)+ 55352 ()) + 16
7 libc++abi.dylib 0x00000001b569f8c4 std::terminate+ 55492 () + 84
8 libdispatch.dylib 0x00000001b5f107e8 _dispatch_client_callout + 36
9 libdispatch.dylib 0x00000001b5eb9320 _dispatch_lane_serial_drain$VARIANT$mp + 592
10 libdispatch.dylib 0x00000001b5eb9e3c _dispatch_lane_invoke$VARIANT$mp + 428
11 libdispatch.dylib 0x00000001b5ec24a8 _dispatch_workloop_worker_thread + 596
12 libsystem_pthread.dylib 0x00000001b60f0114 _pthread_wqthread + 304
13 libsystem_pthread.dylib 0x00000001b60f2cd4 start_wqthread + 4

Side-effects-in-computed-properties

I want to avoid having side effects in my code, but I don't know how to fix these, does some one can help?
computed: {
sumarVerduras(){
this.totalVerduras = 0;
for( const verdura of this.verduras){
this.totalVerduras = this.totalVerduras + verdura.cantidad
} return this.totalVerduras;
}
}
It work as I want but side effect is there
Module Warning (from ./node_modules/eslint-loader/index.js):
error: Unexpected side effect in "sumarVerduras" computed property (vue/no-side-effects-in-computed-properties) at src\App.vue:53:7:
51 | computed: {
52 | sumarVerduras(){
53 | this.totalVerduras = 0;
| ^
54 | for( const verdura of this.verduras){
55 | this.totalVerduras = this.totalVerduras + verdura.cantidad
56 | } return this.totalVerduras;
error: Unexpected side effect in "sumarVerduras" computed property (vue/no-side-effects-in-computed-properties) at src\App.vue:55:11:
53 | this.totalVerduras = 0;
54 | for( const verdura of this.verduras){
55 | this.totalVerduras = this.totalVerduras + verdura.cantidad
| ^
56 | } return this.totalVerduras;
57 | }
58 | }
You should not edit any Vue component's data in computed property. Here you modify this.totalVerduras, which is considered as Vue's component data.
You can change to:
computed: {
sumarVerduras() {
let totalVerduras = 0;
for (const verdura of this.verduras) {
totalVerduras = totalVerduras + verdura.cantidad
}
return totalVerduras;
}
}
You can do this as well:
computed: {
sumarVerduras() {
return verduras.reduce((a, x) => a + x.cantidad, 0);
}
}
This method gets rid of totalVerduras variable and the for loop.

Alamofire 3.5.1 crashed when cancel the upload request

I just followed cnoon's suggest for the request cancel, the steps like:
post the multipartFormData upload request;
catch the upload progress and get the Alamofire.Request in the encodingCompletion;
do cancel request;
Then the crash is coming.
All of the upload related code as below:
private var request: Alamofire.Request?
func upload() {
Alamofire.upload(
.POST,
"\(AppManager_Inst.currentServerAddress)/cloud/uploadFile",
multipartFormData: { [unowned self] multipartFormData in
if self.uploadFile.data.isKindOfClass(UIImage),
let image = self.uploadFile.data as? UIImage,
let imageData = UIImagePNGRepresentation(image) {
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "\(self.uploadFile.name).png", mimeType: "image/png")
}
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}, encodingCompletion: { [unowned self] encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
self.request = upload
upload.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
dispatch_async(dispatch_get_main_queue()) {
let buffer = ["file": "\(self.uploadFile.id)", "speed": "\(bytesRead)", "readed": "\(totalBytesRead)", "all": "\(totalBytesExpectedToRead)"]
GlobalBroadcast_Inst.broadcastMsg(.uploading, msg: buffer)
}
}
upload.responseData(completionHandler: { (response) in
self.uploading = false
let resp = NewFileResp.parseFromData(response.data!)
})
case .Failure(let error):
self.uploading = false
print(error)
}
}
)
}
request?.cancel()
The crash info as below:
*** Terminating app due to uncaught exception 'UninitializedMessage', reason: ''
*** First throw call stack:
(
0 CoreFoundation 0x000000010ceb2d85 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010f322deb objc_exception_throw + 48
2 ProtocolBuffers 0x000000010bb72b69 -[PBGeneratedMessageBuilder checkInitialized] + 169
3 CommonFoundation 0x000000010bd1a17b -[NewFileRespBuilder build] + 43
4 CommonFoundation 0x000000010bd18942 +[NewFileResp parseFromData:] + 130
5 QBCloud 0x000000010b690fe0 _TFFFC7QBCloud8Uploader6uploadFT_T_U0_FOC9Alamofire7Manager31MultipartFormDataEncodingResultT_U0_FGVS1_8ResponseCSo6NSDataCSo7NSError_T_ + 448
6 Alamofire 0x000000010b92c0d7 _TTRXFo_oGV9Alamofire8ResponseCSo6NSDataCSo7NSError__dT__XFo_iGS0_S1_S2___dT__ + 151
7 Alamofire 0x000000010b92bc4d _TFFFC9Alamofire7Request8responseuRxS_22ResponseSerializerTyperFT5queueGSqPSo17OS_dispatch_queue__18responseSerializerx17completionHandlerFGVS_8Responsewx16SerializedObjectwx11ErrorObject_T__DS0_U_FT_T_U_FT_T_ + 797
8 Alamofire 0x000000010b92a494 _TPA__TFFFC9Alamofire7Request8responseuRxS_22ResponseSerializerTyperFT5queueGSqPSo17OS_dispatch_queue__18responseSerializerx17completionHandlerFGVS_8Responsewx16SerializedObjectwx11ErrorObject_T__DS0_U_FT_T_U_FT_T_ + 164
9 Alamofire 0x000000010b8e3bf7 _TTRXFo__dT__XFdCb__dT__ + 39
10 libdispatch.dylib 0x0000000110578d9d _dispatch_call_block_and_release + 12
11 libdispatch.dylib 0x00000001105993eb _dispatch_client_callout + 8
12 libdispatch.dylib 0x00000001105811ef _dispatch_main_queue_callback_4CF + 1738
13 CoreFoundation 0x000000010ce0c0f9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
14 CoreFoundation 0x000000010cdcdb99 __CFRunLoopRun + 2073
15 CoreFoundation 0x000000010cdcd0f8 CFRunLoopRunSpecific + 488
16 GraphicsServices 0x0000000113cd3ad2 GSEventRunModal + 161
17 UIKit 0x000000010dda5f09 UIApplicationMain + 171
18 QBCloud 0x000000010b692b42 main + 114
19 libdyld.dylib 0x00000001105ce92d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type
Does anyone can help on this?
I find the root cause of my problem is the response.data is 0 bytes NSData, so the parseFromData of protobuf failed:
upload.responseData(completionHandler: { (response) in
self.uploading = false
let resp = NewFileResp.parseFromData(response.data!)
})