【问题标题】:Send an image with axios and formidable ( nodejs -> express )发送带有 axios 和强大的图像( nodejs -> express )
【发布时间】:2020-04-23 14:13:03
【问题描述】:

我正在尝试使用 axios (nodejs) 发送图像以表达具有强大功能的服务器。 这是axios脚本的代码:

const axios = require('axios');
const fs = require('fs')
const FormData = require('form-data')

var img = fs.readFileSync("C:/Users/alessio/Documents/FX/screenshot.png", 'utf8'); 
console.log(img)
let data = new FormData();
data.append('img', img, "img.png")
console.log(data);
axios.post('http://192.168.43.193:3000/testAPI/upload_img_mt', data, {
    headers: {
        'accept': 'application/json',
        'Accept-Language': 'en-US,en,q=0.8',
        'Content-Type': `multipart/form-data; boundary=${data._boundary}`,
        'timeout': 999999
    },
})
    .then(function (response){
        //console.log(response);
    })

这是带有 express 的代码服务器端,并且带有强大的响应管理:

router.post('/upload_img_mt', function(req, res, next){
    console.log(req)

    var form = new formidable.IncomingForm();
    form.uploadDir = "fxdiary";
    form.encoding = 'utf8';
    form.on('fileBegin', function(name, file){
        console.log(form.uploadDir + "/" + file.name);
    });
    form.parse(req, function(err, fields, files) {
        console.log(files);
        console.log(err);
        console.log(fields);
    });
    res.sendStatus(200);
});

文件图像已保存,但不是正确的 png 图像。图像的大小不正确,有时会随机变化。广告示例原始文件大小为 33k,变为 900bytes 或 54k 或其他值。

发生了什么?这段代码哪里出了问题?

【问题讨论】:

  • 你能评论 console.log(files);控制台日志(错误);控制台.log(字段);这三个的调试日志
  • 解析的登录回调不在控制台打印。唯一打印的日志在'fileBegin'。

标签: node.js express axios formidable


【解决方案1】:

您不需要在 Content-type 标头中传递边界,因为它是由浏览器自动添加的。你可能会破坏默认的边界机制。

如果您仍然面临文件大小问题,请尝试使用 multer 模块在 Nodejs 端进行文件处理

【讨论】:

  • nodejs 脚本在没有浏览器的情况下运行,如果我删除边界,结果是:错误:错误的内容类型标题,没有多部分边界
  • with multer not work.. 错误是 MulterError: Unexpected field 在响应中(错误 500)
  • 表单追加数据的名称必须与upload.single('name')处理的相同。解决方案的第二部分是 axios 发送的编码:必须与 multer ( 7bit ) 相同。没有指定编码的 fs.readFileSync 完成了剩下的工作。
  • 是的。当我提到 multer 时,我的意思是一样的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-22
  • 2021-12-31
  • 2022-09-23
  • 1970-01-01
  • 1970-01-01
  • 2016-09-14
  • 1970-01-01
相关资源
最近更新 更多