使用React.js发布文件 [英] POST a file with React.js
问题描述
最终用户应该通过文件浏览器上传excel文件:
The end user is supposed to upload through a file browser an excel file:
<FloatingActionButton title="Upload excel" primary className="import-vendor"
containerElement="label"
label="Browse file">
<input onChange={(e) => Actions.uploadXLS(e.target.files[0])}
type="file"
name="xls"
accept="application/vnd.ms-excel"
style={{ display: 'none' }}/>
<UploadIcon/>
</FloatingActionButton>
操作:
uploadXLS(file) {
this.getInstance().callUploadXLS( file );
}
服务:
callUploadXLS: {
remote( state, data ) {
const url = `${base}/vendor/form`;
return $http.instance.api.post( url, data );
},
success: Actions.XLSUploaded,
error: Actions.fail
}
此文件应发送到使用Spring Boot接受的多部分文件构建的POST REST端点.端点无法识别像这样发送文件
This file should be sent to a POST REST endpoint built with Spring boot accepting a multipart file. The endpoint does not recognize sending the file like this
error: "Internal Server Error"
exception :"org.springframework.web.multipart.MultipartException"
message : "Current request is not a multipart request"
path : "/vendor/form"
status : 500
timestamp : 1501747384079
如何发布excel文件?
How can I post the the excel file?
我现在正在尝试发布文件列表:
I am trying now to post a list of file:
const arrayOfFile = [];
let i = 0;
for ( i = 0; i < files.length; i++ ) {
const data = new FormData();
arrayOfFile[i] = data.append( 'file', files[i] );
}
this.getInstance().callUploadXLS( arrayOfFile );
但是data.append('file',files [i]);总是返回未定义的
but data.append( 'file', files[i] ); is always returnin undifined
推荐答案
通过multipart/form-data
表单将文件传递到后端.
Passing a file to the backend is done via multipart/form-data
forms.
如果您现在检查发送到后端的请求,您会发现您的请求没有发送(可能是)multipart/form-data
.
If you inspect the request that you send to the backend right now, you will see that your request does not send ( probably ) a multipart/form-data
.
您可以检查参考信息 enctype ='multipart/form-data是什么是什么意思?问题.
You can check for reference What does enctype='multipart/form-data' mean? question.
您的代码应类似于:
callUploadXLS: {
remote( state, file ) {
// ^ make sure that `file` here is the same target.files[0]. It should be `File` Object
// Will turn your form to `multipart/form-data`
var data = new FormData();
data.append('file', file);
const url = `${base}/vendor/form`;
return $http.instance.api.post( url, data );
},
success: Actions.XLSUploaded,
error: Actions.fail
}
这篇关于使用React.js发布文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!