Home  >  Q&A  >  body text

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>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>
P粉156415696P粉156415696453 days ago514

reply all(1)I'll reply

  • P粉729198207

    P粉7291982072023-08-16 12:27:25

    Yes, I successfully solved my problem. These small modifications are the key:

    const jsonBlob = new Blob(['<jsonText>'], {type: 'application/json'});
    
    let formData = new FormData();
    formData.append('file', jsonBlob, 'filename.json');
    
    const headers = new Headers();
    headers.append('x-auth-token', '<token>');
    
    let payload = {
        method: 'PUT',
        headers: headers,
        body: formData
    }
    
    fetch('https://endpoint.url.here', payload) ...

    Everything is running great now!

    reply
    0
  • Cancelreply