React.js, how to send a multipart/form-data to server

前端 未结 6 1013
走了就别回头了
走了就别回头了 2020-12-14 01:35

We want to send an image file as multipart/form to the backend, we try to use html form to get file and send the file as formData, here are the codes

export          


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-14 02:22

    For sending multipart/formdata, you need to avoid contentType, since the browser automatically assigns the boundary and Content-Type.

    In your case by using fetch, even if you avoid Content-Type it sets to default text/plain. So try with jQuery ajax. which removes the contentType if we set it to false.

    This is the working code

    var data = new FormData();
    var imagedata = document.querySelector('input[type="file"]').files[0];
    data.append("data", imagedata);
    $.ajax({
        method: "POST",
        url: fullUrl,
        data: data,
        dataType: 'json',
        cache: false,
        processData: false,
        contentType: false
    }).done((data) => {
        //resolve(data);
    }).fail((err) => {
        //console.log("errorrr for file upload", err);
        //reject(err);
    });
    

提交回复
热议问题