javascript - React Native 上传图片失败
问题描述
从过去的两天开始,我一直在努力破解使用 React Native 上传到 MongoDB 的文件/图像。我从字面上阅读了所有相关的论坛,但没有运气。我阅读了几个论坛,他们给出了一个示例,但我没有成功。这是我编写的示例代码。
客户端 :
const { uri } = await this.camera.takePictureAsync(options);
let formData = new FormData();
formData.append('file', {
uri: uri.replace("file:///", ""),
type:'image/jpg', name:'userProfile.jpg',
});
const rawResponse = await fetch('http://192.168.1.5:9000/api/contrats/upload', {
method: 'POST',
body: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data; charset=utf-8',
},
});
const content = await rawResponse.json();
console.log(content);
服务器端
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, __basedir + '/resources/static/assets/uploads');
},
filename: (req, file1, cb) => {
console.log("file : ", file);
let name = file.originalname || file.name;
let extension = name.substr((~-name.lastIndexOf(".") >>> 0) + 2);
let filename = generateId() +"."+ extension; nsion;
cb(null, filename)
},
});
var upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
}
});
结果
解决方案
试试下面的
let body = new FormData();
let filename = uri.split('/').pop();
body.append('file', {uri:uri, name:filename, type:'image/jpg', });
const header = {
'Accept': 'application/json',
'content-type': 'multipart/form-data',
}
fetch("http://192.168.1.5:9000/api/contrats/upload", {
method: 'POST',
headers: header,
body:body,
}).then(response => response.json())
.then(res => console.log(res))
.catch(err => console.log("err", err)
推荐阅读
- sharepoint - Sharepoint 工作流 2013,在项目已被特定人员修改时运行
- php - wordpress 中的 Razorpay 插件不起作用
- protractor - 如何在 Protractor 中写入 Excel 文件
- qt5 - 如何使用大球体上的纹理作为背景?
- python - 多类分类:连续多列的 SMOTE 过采样
- python - Pandas 将每 N 列除以固定列
- python - AttributeError:即使安装了 opencv-contrib-python,'module' 对象也没有属性 'face'
- javascript - CSS - 调整大小和溢出隐藏属性不适用于绝对位置
- xml - XML - XSLT - 使用来自外部 xml 文档的属性
- c# - 将数据附加到 SQL - 应在找到唯一记录时插入,否则条件会覆盖现有数据