如何在反应中上传后在请求中发送文件?

时间:2018-02-05 10:40:11

标签: javascript ajax reactjs file-upload

<form id="uploadFile" method="post" enctype="multipart/form-data">
<label className="col-sm-5 form-control-label " for="file">Select a 
file</label>
<div className="col-sm-7">
<input name="file" type="file" multiple />
</div>
</form>

在jsx中我传递了encType。

let formData = new FormData();
formData.append("id", idForUpload);
formData.append("uploadFiles", $('#uploadFile')[0]);
ContractAction._uploadFileToContract(formData);

我想传递id和uploadFiles作为键和值我需要传递文件。但我能够获取id但是uploadFiles没有进入请求

我正在制作如下的ajax

import $ from 'jquery';
import BASEURL from './urlConfig.jsx';
 //import dispatcher from "../dispatchers/dispatcher";

module.exports ={

_callAPI: function(url,method,data,target){

    $.ajax({
        url: url,
        method: method,
        data: formData,
        processData: false,
        contentType: false,
        success: (data,textStatus, jqXHR) => {
            target('success', data);   

        },
        error: (jqXhr,textStatus,error) => {
            target('error',jqXhr,textStatus,error);
            console.log("error inside code", jqXhr,textStatus,error);
        },

    });
},

 }

1 个答案:

答案 0 :(得分:0)

您可能需要阅读文件的内容,然后将其传递。

var file = $('#uploadFile')[0];
var reader = new FileReader();
reader.onload = function(e){
    var content = e.target.result;
    console.log(content);
}
reader.readAsText(file);

您可能想要查找FileAPI FileReader

https://developer.mozilla.org/en-US/docs/Web/API/FileReader

https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications