JS 传各种文件到后端

由于要写一个前端上传文件按钮功能,本人前端是小白,所以在网上搜索了许多,发现FileReader非常好用。

不多BB,直接来。

1,前端只需要一个input标签,

<input type="file" id="file" >

2,JS,很简单

    $("#file").bind("change",function () {
        var fileinfo = document.getElementById("file").files[0];
        var reader = new FileReader();
        reader.readAsDataURL(fileinfo);
        reader.onload = function(){
            //console.log(reader.result);
        };
    })

3,选择了readerAsDataURL 方法 读取数据,因为试过其他方式,发现其他方式获取数据后在传到后端时,容易引起浏览器崩溃。

4,由于readerAsDataURL方法,获取的返回值,并不是完全的数据,而是加了一些前缀。

data = reader.result.split(",")[1]  # 这样才是完整的数据

5,使用ajax发送数据:

jQuery.ajax({
          dataType:"json",
          data:JSON.stringify({"fileinfo":data,"name":filename,"path":path,}),
          url:"/task/getfile/",
          type:"post",
          cache:false,
          processData:false,
          contentType:false,
          success:function (data) {
          if(data.status==0){
          document.getElementById("text_info").innerText = "文件成功上传!"
         }else{
          document.getElementById("text_info").innerText = "文件上传失败!"
       }
      },
  });

6,后端接受数据就OK。由于readAsDataURL将文件转为了base64格式,所以后端只需要转回去就OK了.

7,打开文件(文件名后缀要一致!一致!一致!) ,f.write  都会,就不写了。

8,然后就成功了。

原文地址:https://www.cnblogs.com/stfei/p/10291723.html