My current challenge involves making an api call that necessitates uploading a file in the file=@ format. The api call works perfectly using postman/curl. Here is an example:
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'
However, when attempting to perform this action on the web, I receive a 400 error from the API. I have tried various approaches, and below is my current attempt:
<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>
When I try to convert the frontend code into the file=@ format using devtools, I get the following:
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 modify my frontend code to adhere to the file=@ format instead of the current approach? Alternatively, is there a different method I should consider?
Please let me know if additional information is needed to assist in resolving this issue.