2 years ago

#59652

test-img

猫耳橙橙喵

How to post a downloaded image file using axios?

I'm a beginner to Web Programming and React. So the question is: I have an URL link to a remote image file(.jpg), and I need to upload it as a formData.

I tested success to upload local files like this:

const fileRef = useRef(null);
const callback = useCallback(e => {
    let formData = new FormData();
    formData.append("file", fileRef.current.files[0]);
    axios.post('url', formData).then(res => { // ... })
}, [fileRef])

return (
    <div>
        <input type="file" ref={fileRef} />
        <button onClick={callback} >Upload Local File</button>
    </div>
);

When I tried to download a remote file object, I saved it with a Blob:

const imgURL = 'path_to_remote_image_file';
const [file, setFile] = useState(null);
useEffect(() => {
    axios({url: imgURL, method: "GET", responseType: "blob"}).then(res => {
        const file = new Blob([res.data]);
        setFile(file);
    }
}, [])

But when I replace the appended file with this blob object formData.append("file", file); , I got an error from the server.

By using Chrome's devTools I found that when I upload a local image, the binary formData uploaded was marked as below:

Content-Disposition: form-data; name="file"; filename="file.jpg"
Content-Type: image/jpeg

But when I upload the remote image, the binary formData uploaded was this:

Content-Disposition: form-data; name="file"; filename="blob"
Content-Type: application/octet-stream

So how can I correctly transform the downloaded binary data to correctly upload it? Should I use a File rather than a Blob, or should I use another data type to store the remote image?


Update: I tried to replace new Blob([res.data]) with new File([res.data], "filename.jpg") and it managed to work. I checked for the binary data in DevTools and the content type is still application/octet-stream. So I asked for the API developer and learned that they are treating anything uploaded as a image file and only check the filename. It seems that even after I using File() to specific a name for it, the MIME type is still application/octet-stram.

I checked the File() document in MDN and learned that it can accept third argument to change the MIME type. So I wonder where I could grab the MIME type info from axios?

And also where I could grab the file name as some of the image url link does not have a file extension and NOT all remote files are jpeg format.


Update Again:

It seems that the response header "Content-type" will provide me the MIME type of the response file data. And it depends on the server whether and where the filename is included in the response.

javascript

axios

form-data

0 Answers

Your Answer

Accepted video resources