原生js上传图片遇到的坑

后台给我写了一个上传图片的接口,自己用form表单测试成功

 接口可以正常跳转

 测试的代码:

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>
 </head>
 <body>
  <form method="POST" action="http://192.168.79.191:8889/api/upload/uploadFile" enctype="multipart/form-data">
    <table>
        <tr>
            <td><label path="file">Select a file to upload</label></td>
            <td><input type="file" name="file" id="upload_file"/></td>
        </tr>
        <tr>
            <td>fileGroup: <input name = "fileGroup" type = "text"><br></td>
        </tr>
        <tr>
            <td>flag:<input name = "flag" type = "text"><br></td>
        </tr>
        <tr>
            <td><input type="submit" value="Submit"/></td>
        </tr>
    </table>
</form>
 </body>
</html>
View Code

因为这样用form表单提交的时候会自动跳转,所以就想到用js模拟form表单提交

代码一写完,问题来了,用axios请求不成功,然后换成了原生的ajax请求还是不成功,代码如下

/*原生请求方式 */
let xhr = new XMLHttpRequest();  // XMLHttpRequest 对象
xhr.open("post", "http://localhost:8082/api/files/api/upload/uploadFile", true); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。
xhr.setRequestHeader('content-type', 'multipart/form-data')//不要自作多情加上这一句
//xhr.setRequestHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8')
xhr.send(formData); //开始上传,发送form数据
xhr.onreadystatechange = function () {
    var data = xhr.responseText;
    console.log(data);
}

控制台 network  就是请求不成功,500报错

 错误信息如下

整了大半天,最后发现是不用设置content-type   一去掉就正常了  真的是自作多情 自己设置了content-type导致请求不成功

猜你喜欢

转载自www.cnblogs.com/pengfei25/p/11907750.html
今日推荐