javascript - why I use fetch to upload img in react don't have fileName? -
i use fetch upload images in react,my code below:
let formdata = new formdata(); let file = {uri: imgdata, type: 'multipart/form-data', name: '2_resources.jpg'}; formdata.append("name", "name"); formdata.append("mobile", "18381307123"); formdata.append("content", "123654"); formdata.append("resources", file,"2_resources.jpg");//mind line fetch(config.report, { mode: 'cors', method: "post", body: formdata }) .then(res => res.json()) .then((data) => { console.log(data) } ).catch((err) => { console.log(err) } );
i have formdata
api document on https://developer.mozilla.org/en-us/docs/web/api/formdata have write below:
and fetch used :"isomorphic-fetch": "^2.2.1"
what should use fetch upload images? thanks.
you adding file formdata object incorrectly. isomorphic-fetch wraps github's fetch polyfill. looking @ docs shows should be:
handlefileupload(event) { var formdata = new formdata(); formdata.append('filename', event.target.files[0]); fetch('http://your-domain/upload', { mode: 'cors', method: 'post', body: formdata }).then(function (response) { console.log('response: ', response); }); }
the field name on server whatever use key when appending formdata. in above example 'filename'. don't think need set content-type , file name yourself. should set automatically.
in above example, 'event' event fired input tag when user upload file:
<input type="file" onchange={this.handlefileupload}/>
Comments
Post a Comment