首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从Angular端发送文件后,在Node.js端编码大文件时出错

从Angular端发送文件后,在Node.js端编码大文件时出错
EN

Stack Overflow用户
提问于 2018-08-09 17:13:00
回答 2查看 984关注 0票数 2

我在服务器端以console.log(body)的身份获取文件。

代码语言:javascript
复制
{ fieldname: 'image',
  originalname: '21329726_1866651723650020_188839340_o.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: './pics/',
  filename: '5146c9818ff517c426e34ad84ff3513f',
  path: 'pics/5146c9818ff517c426e34ad84ff3513f',
  size: 94093 
}

然后用const base64Data = body.buffer.toString("base64")进行编码。

但对于小文件,它工作得很好,但对于大文件,它会产生问题。它没有正确编码。

我认为问题是由于,它在接收完整文件之前就开始编码了。

请给我一些合适的方法。

这是我的GitHub链接here

EN

回答 2

Stack Overflow用户

发布于 2018-08-12 09:40:32

我认为如果不在前端将pdf文件转换为base64会更好,因为base64更大,这会增加请求开销。最好使用html5 FormData上传文件和其他请求负载。尝试使用这些更改。

直接将文件值分配给您的文档属性。

代码语言:javascript
复制
 this.uploadForm.patchValue({
    document: event.target.files[0]
 });
  //inside your service enrich your data with FormData ,set content-type to undefined and send it
 uploadData (uploadForm) {
    //enrich your data is FormData
    let fd= new FormData();
    // try looping through `this.form.controls` or uploadForm, to assign it property key and value dynamically
    fd.append('branch', branch_value);
    fd.append('semester', semester_value);
    fd.document('document',document_value)
    return this.http.post<RegisterResponse>('/user/upload', fd,set_header_config);
 }

确保将content-type正确设置为undefined。我测试过用angularjs上传文件,但对最新的角度变化不是很熟悉。

你可以查看下面的博客:http://learnwebtechs.com/2017/04/22/angularjs-multiple-file-upload-using-http-service

票数 2
EN

Stack Overflow用户

发布于 2018-08-13 16:59:31

在/server/routes/user.js中更新以下代码

代码语言:javascript
复制
const express = require('express');
const router = express.Router();
// const mongoose = require('mongoose');
const path = require('path');
const multer = require('multer');

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, __basedir + '/upload');
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname)
  }
})

const upload = multer({
  storage: storage,
  limits: {
    maxFileSize: 1024 * 1024 * 5
  }
}).single('filename');

router.post('/upload', upload, (req, res) => {
  res.send('uploaded');
});

router.post('/submit', (req, res) => {
  console.log(req.body);
});

module.exports = router;

还可以在app.js中添加以下行

代码语言:javascript
复制
global.__basedir=__dirname;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51763117

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档