我有一个api调用,需要我通过file=@格式上传文件。我使用postman/curl让它按预期工作。
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'当我尝试通过网络来做这件事时,我从API得到了400的回报。我已经尝试了几种不同的方法,这里是我当前的示例。
<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>如果我在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我如何在这里更新我的前端代码,以获得file=@格式的代码而不是数据...或者还有其他方法来解决这个问题呢?
如果需要更多信息来帮助解决这个问题,请让我知道。
发布于 2019-02-13 08:37:28
这个问题是因为发送了一个内容类型的头文件,但是这应该被省略,浏览器将自动使用默认的内容类型,这使我能够通过web上传文件。
https://stackoverflow.com/questions/54642045
复制相似问题