Home >Web Front-end >JS Tutorial >Code to upload ajax files using FormData()
This article introduces to you the code about using FormData() to upload ajax files. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
HTML:
<form action=""> <input type="file" id="file1" name=""> <br> <input type="file" id="file2" name=""> <br> <input type="button" value="保存"> </form>
JS:
$("input[type='button']").on('click', upfile); /** * [upfile 文件上传] * @return {[Object]} [成功回调] */ function upfile() { var formData = new FormData(); formData.append("接收字段1", document.getElementById('file1').files[0]); // console.log(document.getElementById('file1').files[0]); formData.append("接收字段2", document.getElementById('file2').files[0]); // console.log(document.getElementById('file2').files[0]); $.ajax({ url: '接口地址url', type: 'POST', data: formData, // 上传formdata封装的数据包 dataType: 'JSON', cache: false, // 不缓存 processData: false, // jQuery不要去处理发送的数据 contentType: false, // jQuery不要去设置Content-Type请求头 success: function(data) { // 成功回调 console.log(data); } }); }
Successful effect:
Related recommendations:
The animation effect of loading before the ajax request is completed
How is the path object of nodeJs used to handle directories? (Code)
The above is the detailed content of Code to upload ajax files using FormData(). For more information, please follow other related articles on the PHP Chinese website!