typescriptvue.jsamazon-s3axios

How to use axios to get a file stored in s3


I have a function I was trying to develop to return a file from s3 but it does not actually return a working file that could open in the browser:

export async function urlToFile (url : string, fileName: string) : Promise<File> {
    let file = null
    await axios.get(url).then(response => {
        file = response.data
    })
    return new File([file], fileName)
  }

However, this code I found on stack overflow does work and say a pdf could open in the browser if I tried. However, the issue is I have to manually add the mimpe type and I cannot figure out how to get this from the download url:

        export function urltoFile(url, filename, mimeType){
    if (url.startsWith('data:')) {
        const arr = url.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[arr.length - 1]), 
            n = bstr.length, 
            u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        const file = new File([u8arr], filename, {type:mime || mimeType});
        return Promise.resolve(file);
    }
    return fetch(url)
        .then(res => res.arrayBuffer())
        .then(buf => new File([buf], filename,{type:mimeType}));
}

I would prefer to use axios but if its not doable I am willing to use this second approach but need help getting the mime type.


Solution

  • You could specify the response type on your axios request as a blob. The mime type would then be contained in the response header content-type. Modify your code as follows:

    export async function urlToFile(url: string, fileName: string): Promise<File>{
      const response = await axios.get(url, {
        responseType: 'blob'
      });
    
      const fileData = response.data;
      const mimeType = response.headers['content-type'];
      
      return new File([fileData], fileName, {type: mimeType});
    }