从今天早上开始,我一直遇到一个问题,一直困扰着我……实际上,我正在尝试使用载波将文件上传到AWS S3(我在react_on_rails上)。它与rails form builder配合得很好,因此不是载波故障,而是我的react.js组件。
我的组件:
import PropTypes from 'prop-types';
import React from 'react';
import { log } from 'util';
import { resolve } from 'upath';
export default class Form extends React.Component {
static propTypes = {
url: PropTypes.string.isRequired,
};
/**
* @param props - Comes from your rails view.
*/
constructor(props) {
super(props);
this.state = {
sound: '',
};
}
submitGroupForm = (event) => {
event.preventDefault();
fetch(this.props.url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-CSRF-Token': ReactOnRails.authenticityToken(),
// 'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
band_music: {
sound: this.state.sound,
}
}),
}).then((response) => {
console.log(response)
}).then((err) => {
console.log(err);
})
}
onChange = (e) => {
this.setState({ sound: e.target.files[0] });
}
render() {
console.log(this.state)
return (
<div>
<form onSubmit={this.submitGroupForm}>
<div className="form-group">
<label htmlFor="sound" className="color-primary">
mp3 file
</label>
<div className="row justify-content-center align-items-center">
<input
id="sound"
type="file"
name="sound"
onChange={(e) => this.onChange(e)}
/>
</div>
</div>
<div className="row justify-content-center">
<input className="btn btn-lg bg-button color-white mt-3" type="submit" value="Post the file" />
</div>
</form>
</div>
);
}
}
我遇到的最大问题是该文件未通过Json传递,它创建了一个javascript File对象,当它通过API传递时,它将值解释为{}
。我试图将此File对象转换为base64,但仍然无法正常工作。...
有什么主意吗?