问题
I am trying to upload a document / image file to server. I tried using fetch (multipart), as well as XMLHttpRequest. The same thing is working fine with Postman.
1) using fetch multipart ---- getting network request failed
export async function upload(url, res, uploadedFileName) {
var data = {
file1: {
uri: res.uri,
type: res.type,
name: uploadedFileName,
}
};
let options = {
headers: {
'Content-Type': 'multipart/form-data'
},
method: 'POST'
};
options.body = new FormData();
for (let key in data) {
options.body.append(key, data[key]);
}
options.body.append('jsonKey', {CompanyName:"Test"});
return new Promise(
function (resolve, reject) {
fetch(url, options)
.then(
function(response) {
if (response.ok) {
resolve(response.json());
}
else {
console.log('response = '+JSON.stringify(response))
reject(new Error(`Invalid response received - (${response.status}).`));
}
}
)
.catch(
function(error) {
var errorMsg = error.message;
if(errorMsg === 'Network request failed') {
errorMsg = 'Please check your network / internet connection.'
}
reject(new Error(`${errorMsg}`));
}
);
}
);
}
2) Using XMLHTTPRequest --- getting error 406
export async function uploadXHR(url, res, uploadedFileName) {
var data = {
file1: {
uri: res.uri,
type: res.type,
name: uploadedFileName,
}
};
var formData = new FormData();
for (let key in data) {
formData.append(key, data[key]);
}
formData.append('jsonKey', {CompanyName:"Test"});
var xhr = new XMLHttpRequest();
return new Promise(
function (resolve, reject) {
xhr.open("POST", url);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
// console.log('StatusText: '+xhr.statusText);
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
}
);
}
NOTE: The fetch method works well, when no additional param is needed, except the file itself. But in case of sending additional param, it gets failed.
来源:https://stackoverflow.com/questions/62309620/unable-to-upload-document-file-to-server-using-fetch-xmlhttprequest-in-react