简体   繁体   中英

upload static file with axios as formdata

i am looking to uplaod static file to server with axios how can achieve this:

import pdf from "./sample.pdf"

const formData = new FormData()
formData.append("file",pdf)

await axios.post("upload",formData, {headers: {'Content-Type': `multipart/form-data; 
boundary=${formData._boundary}`}})

also i tried to create new file with javascript File() construct like so: const file = new File([pdf], name + '.pdf', {type: 'application/pdf'}); but its turn out the file will be empty with unsupported type.

so how can i covert the static file to formData any help,thanks.

Convert pdf to base64 and then append it formData.

When you import a pdf file and do a console.log you will see the url (not file blob/data).

You can fetch the pdf file and in the then block, make a post request.

Like this

import test from "./test.pdf";
import axios from "axios";

export default function App() {
  useEffect(() => {
  console.log('test', test); //<---this prints just the url
    axios.get(test).then(pdf => {
      console.log(pdf.data);//<---this prints the base64

      const formdata = new FormData();
      formdata.append("pdf", pdf.data);
      formdata.append("name", "whatever");

      axios
        .post("", formdata, {
          headers: {
            "content-type": "multipart/form-data"
          }
        })
        .then(res => {});
    });
  }, []);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

this how i did it: first i turn the imported file to base64 using this function:

   const data = await axios.get(url, {responseType: 'arraybuffer'}).then((response) => 
          {
      let pdf= btoa(new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
      return `data:${response.headers['content-type'].toLowerCase()};base64,${pdf}`;
    });

then convert the base64 to file object:

  function dataURLtoFile() {
      var arr = data.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);

      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }

      return new File([u8arr], name + '.pdf', {type: mime});
    }

and finally executed the 2 function to get result:

    const pdf = await dataURLtoFile();
    bodyFormData.append('pdf', pdf);
    await sendReport(bodyFormData);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM