react 原生上傳方法
import React, {Component} from 'react';
class FetchUpload extends Component {
constructor(props) {
super(props);
this.fileInput = React.createRef();
}
upload = () => {
const data = new FormData();
console.log(data);
let json_data = {
name: '2323',
singer: 'ce',
sing_type: 1
};
data.append('name', JSON.stringify(json_data.name));
data.append('singer', JSON.stringify(json_data.singer));
data.append('sing_type', JSON.stringify(json_data.sing_type));
data.append('file', this.fileInput.current.files[0]); //相當於 input:file 中的name屬性
fetch('http://192.168.1.162:8080/v1/user/upload-music', {
method: 'POST',
body: data,
headers:{
'Authorization':"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzcyMjI4NTgsImlhdCI6MTU3NTQyMjg1OCwidWlkIjoxMDAwMTAyfQ.s46-RlXnfKBcloLHU-GeYJ2pFfveIdPZ5UCuxCQM6mM"
}
}).then(response => console.log(response))
};
render() {
return (
<div>
<input type="file" name='file' ref={this.fileInput}/>
<input type="button" value="上傳" onClick={this.upload}/>
</div>
)
}
}
export default FetchUpload;