简体   繁体   English

使用JavaScript通过file = @格式上传文件

[英]Upload file via file=@ format using javascript

I have an api call that requires me to upload a file via file=@ format. 我有一个api调用,要求我通过file = @格式上传文件。 I have it working as expected using postman/curl eg 我使用邮递员/卷曲例如按预期工作

curl -X POST \
    'http://localhost/test' \
    -H 'Authorization: Bearer ...' \
    -H 'Content-Type: application/x-www-form-urlencoded' \
    -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
    -F 'file=@C:\Users\aaa\Downloads\testdata.xlsx'

When I try and do it via the web I am getting a 400 back from the API. 当我尝试通过网络进行操作时,我从API中获得了400。 I have tried a few different things here is my current example. 我已经尝试了一些不同的方法,这是我当前的示例。

<form id="test-form">
    <input id="file-import" type="file" name="file">
    <div id="test">upload file</div>
</form>


<script>

jQuery(document).on('click', '#test', function (e) {
    var data = new FormData();
    data.append("file", jQuery('#file-import')[0].value);

    var xhr = new XMLHttpRequest();

    xhr.open("POST", "http://localhost/test");
    xhr.setRequestHeader("Authorization", "Bearer " + sessionStorage.t);
    xhr.setRequestHeader("Content-Type", "multipart/form-data;         boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");

    xhr.send(data);
});
</script>

If I right click in devtools and copy as curl command I get the below. 如果我右键单击devtools并复制为curl命令,则会得到以下内容。

curl "http://localhost/test" 
-H "Authorization: Bearer ..." 
-H "Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" 
--data-binary ^"------WebKitFormBoundaryW0inUk99iHMiw7fd^

Content-Disposition: form-data; name=^\^"file^\^"^

^

C:^\^\fakepath^\^\testdata.xlsx^

------WebKitFormBoundaryW0inUk99iHMiw7fd--^

^" --compressed

How can I update my frontend code here to get it in the file=@ format instead of data .... or is there another way to approach this? 我如何在这里更新我的前端代码,使其以file = @格式而不是data ....格式获取?或者还有另一种方法可以解决此问题?

Let me know if any more information is required to help solve this. 让我知道是否需要更多信息来帮助解决此问题。

造成此问题的原因是,正在发送内容类型标头,但是应将其省略,浏览器将自动使用默认的内容类型,使我能够通过Web上传文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM