HTML代码
<input id="daoruInput" type="file"/>
JS代码
var formdata = new FormData();
formdata.append("file", $("#daoruInput")[0].files[0])$.ajax({url: "xx.xx/upload",type: "POST",dataType: "json",data: formdata,//让jquery不处理发送的数据contentType: false, //这里不要落下//让jquery不设置content-type请求头processData: false,//这里不要落下//如果有需要要携带请求头headers: {"Authorization":"Bearer "+localStorage.getItem("access_token")},success: function (ret) {console.log('success')},error: function (err) {console.log('error')},
});
说明:
(1)$('#')[0].files 才可以获取到文件数据
(2)ajax请求的processData属性设置为false,默认情况下为true,会将数据处理为对象格式
(3)ajax请求的contentType属性设置为false,默认情况下为"application/x-www-form-urlencoded",该格式支持大多数数据的上传
原文链接:https://blog.csdn.net/weixin_41305441/article/details/100690312
参考:formData和input的file结合使用 外加面试题 如何用原生实现上传?_new formdata()中添加file-CSDN博客
如何通过ajax实现同时上传文件及普通表单 - 一文了解FormData_ajax上传文件-CSDN博客