How to use the Fetch API to upload string data as a JSON file to a form data endpoint that you want to point to a local file
P粉156415696
2023-08-15 23:09:47
<p>I want to update a hosted Json file using an API on a third-party CDN. In their documentation they provide an example using cURL to accomplish this. A correct cURL request should be like this: </p>
<pre class="brush:php;toolbar:false;">curl -X PUT 'https://endpoint.url.here'
-H 'x-auth-token: <token>'
-F 'file=@"path/to/your/file"'</pre>
<p>Right now I'm building a React page where you enter Json text into a text field and once a button is pressed I want to simulate having a path to the json file so that it can be put into this request. </p>
<p>I basically have two questions:</p>
<ol>
<li><p>I am restricted from using the Fetch API, how can I construct a Fetch request to correctly reflect the example cURL request? </p>
</li>
<li><p>How do I convert a string in a text field to a file path (preferably ending with a filename) so that the endpoint accepts it? </p>
</li>
</ol>
<p>I tried converting the file data to a Blob and using the object URL as the path like this: </p>
<pre class="brush:php;toolbar:false;">const file = new Blob([jsonText], {type: 'text/plain'});
var blobURL = URL.createObjectURL(file);</pre>
<p>I also tried using FormData to set up my request: </p>
<pre class="brush:php;toolbar:false;">let formData = new FormData();
formData.append('file', blobURL);
let headers = {
'x-auth-token': '<token>',
'Content-Type': 'multipart/form-data'
}
let payload = {
method: 'PUT',
headers: headers,
body: formData
}
fetch('https://endpoint.url.here', payload) ...</pre>
<p>When I try to do this, the backend just replies with some errors like "File not provided" and I suspect my request doesn't meet the requirements. Is there a better way to accomplish this? Do you have any suggestions I could try to better match their sample request? </p>
Yes, I successfully solved my problem. These small modifications are the key:
Everything is running great now!