我的输入字段为:
<input
type="file"
className="custom-file-selector-input"
data-qa="custom-file-selector-input"
accept="text/csv"
onChange={this.handleFileInputSelectorChange}
ref={element => (this.fileSelectorRef = element)}
/>
我的handleFileInputSelectorChange函数如下所示:
handleFileInputSelectorChange(event) {
let selectedCsvFile = event.currentTarget.files[0];
let fileReader = new FileReader();
fileReader.onload = e => {
this.setState({
fileResult: fileReader.result,
uploadFile: true,
**selectedCsvFile: selectedCsvFile**,
selectedCsvFileName: selectedCsvFile.name
});
};
fileReader.readAsText(selectedCsvFile);
}
我有一个上传按钮,我在其中调用一个将我的请求发布到服务器的服务:
const file = this.state.selectedCsvFile;
**let formData = new FormData();
formData.append("file", file);**
uploadCsv(someUrl, formData)
.then(response => {
return response.json();
})
.then(data => {
console.log("data", data);
})
.catch(error => {
console.log("error", error);
});
我不确定将文件追加到FormData的方式是否正确。作为回应,我收到错误代码500。
我发布请求的功能如下。
export const uploadCsv = (url, formData) => {
let authHeader = new Headers({
"Authorization": `Bearer MY-CUSTOM-AUTH-TOKEN`
});
return fetch(url, {
method: "POST",
body: formData,
headers: authHeader
}).then(res => {
if (res.ok) {
return res.json();
} else {
if (res.status === 401)
return renewAuthToken(authPost, url, formData);
else
return handleErrorResponse(res);
}
});
};
任何人都可以帮助我解决我的问题。我对ReactJ和整体UX编程还是有些陌生。不确定这是否是通过POST方法发布文件的方式