使用 axios 将 Blob URL 转换为文件对象 [英] Convert Blob URL to file object with axios

查看:109
本文介绍了使用 axios 将 Blob URL 转换为文件对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图像裁剪器,可以为每个裁剪创建一个 blob 文件.

当用户完成裁剪后,他点击了一个成功按钮,我得到了一个如下所示的 URL:blob:

我认为这是因为图像无法在控制台中显示,但是当我尝试调用r.blob()"时,我得到了这个:

<块引用>

r.blob 不是函数

如何更改我的 axios 调用,使其像上面的 fetch 调用一样工作?

旁注:我不知道我的回复将使用哪种文件类型(除了它是图像),所以它可能是 png、jpg、gif 等.

解决方案

显然我的尝试有点矫枉过正.这是对我有用的解决方案:

const config = { responseType: 'blob' };axios.get(blobUrl, config).then(response => {新文件([响应数据],文件名);});

I have an image cropper that creates a blob file for each crop.

When the user finished cropping he clicks a success button and I get an URL that looks like this: blob:https://localhost:5001/4434606b-29c4-483d-a1fc-1cefe50a3e3a". Since I need a file object (so I can post it to my server) I convert this blob into an actual file object with this code:

const file = await fetch(blobUrl).then(r => r.blob()).then(blobFile => new File([blobFile], fileName, { type: blobFile.type }));

This code works, but unfortunately, I need to provide IE11 support and since fetch is not supported (and polyfills don't seem to work for this fetch call) I would like to migrate this statement into axios (which I already use all over my application).

This is what I've tried:

axios.get(blobUrl).then(r => r.blob()).then(blobFile => new File([blobFile], fileName, { type: blobFile.type }));

When I look at the response from the first call (then(r => r.blob()) I get something like this:

I assume this is because the image can't be displayed in the console, but when I try to call "r.blob()" I get this:

r.blob is not a function

How can I change my axios call to work like the fetch call above?

Side note: I don't know which file type my response will have (except that it's an image), so it could be a png, jpg, gif etc.

解决方案

Apparently what I tried was a bit overkill. Here's the solution that worked for me:

const config = { responseType: 'blob' };
axios.get(blobUrl, config).then(response => {
    new File([response.data], fileName);       
});

这篇关于使用 axios 将 Blob URL 转换为文件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆