一段时间以来一直在努力解决这个问题,并且确实需要解决它。
我react-dropzone
用来在 React-Redux 应用程序中设置文件上传。它似乎正在工作,因为它说它已成功发送到服务器,但服务器(Django REST Framework
)收到的内容似乎是一个空的MultiValueDict
。但是,请求有效负载具有以下内容:
------WebKitFormBoundaryWiq9rPvu5bpEoR4X
Content-Disposition: form-data; name="file"
[object File]
------WebKitFormBoundaryWiq9rPvu5bpEoR4X--
所以也许前端很好,但服务器端正在发生一些事情。试图找出问题发生的确切位置。我只知道console.log(formData)
似乎并不表示文件已附加在那里。
无论如何,这是我的代码:
// ./containers/documents/submit_documents.js
import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { submitDocument } from '../../actions/documents';
import Dropzone from 'react-dropzone';
class SubmitDocuments extends Component {
constructor() {
super();
this.state = {
files: []
}
this.handleClick = this.handleClick.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.onDrop = this.onDrop.bind(this);
}
handleClick(event) {
this.setState({
files: []
});
}
handleSubmit(event) {
event.preventDefault();
this.props.submitDocument(this.state.files);
}
onDrop(files) {
// console.log(files);
// files.push(this.state.files);
this.setState({
files
});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div className='panel panel-default'>
<div className='panel-heading'>
<h4><strong>Submit Documents</strong></h4>
</div>
<div className='panel-body'>
<Dropzone className='dropzone' onDrop={this.onDrop}>
<h3>Click to add files or drag files here to upload</h3>
</Dropzone>
<div>
{_.map(this.state.files, f =>
<h5 key={f.name}>{f.name} - {f.size} bytes</h5>
)}
</div>
<button type='submit' className='btn btn-primary'>Submit</button>
<button type='button' className='btn btn-danger' onClick={this.handleClick}>Cancel</button>
</div>
</div>
</form>
);
}
}
function mapStateToProps(state) {
return {
documents: state.home.documents
}
}
export default connect(mapStateToProps, { submitDocument })(SubmitDocuments);
以及相关的动作文件:
// ../actions/documents.js
import axios from 'axios';
import { push } from 'react-router-redux';
import { ROOT_URL } from '../../config/config.json';
// Establish the different types
export const DOCUMENTS = 'documents';
// Creates the error state to be used in components
export function submitDocument(files) {
const formData = new FormData();
formData.append('file', files);
console.log(formData);
return function(dispatch) {
axios
.post(
`${ROOT_URL}/api/documents/fileupload`,
formData,
{ headers:
{
'content-type': 'multipart/form-data',
'Authorization': 'JWT ' + sessionStorage.getItem('token')
}
}
)
.then(response => {
console.log('Success')
})
.catch(error => {
console.log('Failed');
});
}
}
似乎服务器正在期待一个带有 的键值对file
,这似乎应该是用创建的,formData.append('file', files);
但在那里看不到任何类似的东西。
谢谢您的帮助!