简体   繁体   中英

JS FormData sends file as application/ocet-stream, how to set it as multipart/form-data?

As in the title, I'm trying to upload file to Spring Rest Controller using:

handleOnChange() {
    let inputFile = document.getElementById("file-input");
    this.file.file = inputFile.files[0];
    this.file.filename = inputFile.value;
}

render() {
    return (
        <div className="file-input">
                <input id="file-input" type="file"
                    onChange={(event) => this.handleOnChange()} />
        </div>
    );
}

upload() {
let formData = new FormData();
formData.append("file", this.data.file.file, "/D:/temp/test2.xlf");
formData.append("request", JSON.stringify(request));

let reqOptions = {
    method: 'POST',
    body: formData
}

fetch('http://127.0.0.1:8081/multi-mt-evaluation/report', reqOptions)
    .then(response => response.json())
    .then(data => console.log(data));
}

But when fetch is called the file is sent as application/octet-stream, is there a simple, or more complicated way to set it as multipart/form-data?

Try specifying the content type by adding it to your request headers:

let reqOptions = {
    method: 'POST',
    body: formData,
    headers: {
          'Content-Type': 'multipart/form-data',
    },
}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM