uniapp上传图片时,提示不是一个有效的Blob类型,如何转成有效的blod类型
时间: 2024-03-11 22:49:34 浏览: 66
在uniapp中上传图片时,可以使用uni.uploadFile API来实现。如果你要将图片文件转换为Blob类型,可以通过以下方法实现:
```javascript
// 获取图片文件
const file = event.target.files[0];
// 将文件转换为Blob类型
const blob = new Blob([file], { type: file.type });
// 使用uni.uploadFile上传文件
uni.uploadFile({
url: 'your upload url',
filePath: file,
name: 'file',
header: {
'content-type': 'multipart/form-data'
},
success: (res) => {
console.log(res);
},
fail: (err) => {
console.log(err);
}
});
```
在上面的代码中,我们首先获取用户选择的图片文件对象。然后,我们使用`new Blob([file], { type: file.type })`方法将文件对象转换为Blob类型,并指定文件类型。最后,我们使用`uni.uploadFile`方法上传文件,其中的`filePath`参数指定了要上传的文件路径,`name`参数指定了上传文件的名称,`header`参数指定了请求头。在上传成功或失败时,分别会执行相应的回调函数。
相关问题
uniapp 上传图片临时文件转成Blob
以下是uniapp上传图片临时文件转成Blob的方法:
```javascript
// 引入toBlob插件
import toBlob from 'toblob'
// 将图片转为base64
let base64 = 'data:image/png;base64,iVBORw0KG...'
// 将base64转为Blob
toBlob.base64ToBlob({b64data: base64, contentType: 'image/png'}).then(res => {
// res即为转换后的Blob对象
console.log(res)
})
```
uniapp手机上传图片blob转成base64
你可以使用uniapp的`uni.getImageInfo`方法获取图片的信息,然后使用`uni.getFileSystemManager().readFile`方法将图片转换为base64格式。下面是一个示例代码:
```javascript
uni.getImageInfo({
src: imagePath,
success: function (res) {
uni.getFileSystemManager().readFile({
filePath: res.path,
encoding: 'base64',
success: function (data) {
var base64Image = 'data:image/' + res.type + ';base64,' + data.data;
console.log(base64Image);
},
fail: function (error) {
console.log(error);
}
});
},
fail: function (error) {
console.log(error);
}
});
```
在上面的代码中,`imagePath`是图片的路径。首先使用`uni.getImageInfo`方法获取图片的信息,然后使用`uni.getFileSystemManager().readFile`方法读取图片文件并将其转换为base64格式。最后,可以在成功回调函数中获取到转换后的base64图片数据。
请注意,这个方法需要在真机上测试,因为在H5端可能会受到跨域限制。