FormData解决ajax上传文件的问题及ajax跨域

xiaoxiao2021-02-27  270

通过FormData对象可以组装一组用XMLHttpRequest发送请求的键/值对。它可以更灵活方便的发送表单数据,因为可以独立于表单使用。如果你把表单的编码类型设置为multipart / form-data,则通过FormData传输的数据格式和表单通过submit()方法传输的数据格式相同* Html代码部分*

<div id =“uploadForm”> <input id =“file”type =“file”name = “musicname”/> <button id =“upload”type =“button”> upload </ button> </ div> * javaScript *

“` (function(){ (function(){ (“#upload” ).click(function(){ var formData = new FormData(); formData.append('file', file[0].files[0]; ( ′ # f i l e ′ ) [ 0 ] . f i l e s [ 0 ] ) ; .ajax({ url:’ http://127.0.0.1:8080/xxxx 类型:’POST’,

cache:false, data:formData, processData:false,//不处理数据 contentType:false //不设置内容类型 })。done(function(res){ })。fail(function(res){}); }); }); ```FormData对象的字段类型可以是Blob,File或者字符串:

response.setHeader(“Access-Control-Allow-Origin”,“*”); response.setHeader(“Access-Control-Allow-Methods”,“POST,GET”);

转载请注明原文地址: https://www.6miu.com/read-10905.html

最新回复(0)