Multer 不将文件另存为文件

Multer not saving file as file

我在路由上设置了 multer 作为中间件。当命中该路由时,multer 不会下载该文件。这是 console.log 报告的内容:

{ firstname: 'foo',
  lastname: 'foo',
  username: 'foo10',
  password: 'test1234',
  file: '/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAAB.....

}

我有以下 multer 设置:

var storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null,  '../images/profile');
  },
  filename: function(req, file, cb) {
    cb(null, req.body.username + '.jpeg');
  }
});

var upload = multer({storage: storage});

router.post('/auth/signup', upload.single('file'), function(req,res) {
  console.log(req.body);
});

所以问题在于,它没有将文件保存为文件,而是将其简单地视为表单中的另一个键值对。

为了进一步说明,我从 cordova API 获得了这张图片: http://ionicframework.com/docs/v2/native/camera/

import { Camera } from 'ionic-native';

Camera.getPicture(options).then((imageData) => {
 // imageData is either a base64 encoded string or a file URI
 // If it's base64:
   let base64Image = 'data:image/jpeg;base64,' + imageData;

   let formData: FormData = new FormData(),
        xhr: XMLHttpRequest = new XMLHttpRequest();     
        formData.append("file", base64Image);

        xhr.onreadystatechange = () => {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                observer.next(JSON.parse(xhr.response));
                observer.complete();
            } else {
                observer.error(xhr.response);
            }
          }
        };
      xhr.open('POST', 'http://localhost:8080/auth/signup', true);
      xhr.send(formData); 

}, (err) => {
 // Handle error
});

文件数据正在作为 Base64 字符串上传,这表明它没有作为正确的 File 表单数据字段上传。这就是为什么 multer 将其视为常规字段,而不尝试将其保存到文件中的原因。

this answer 中,提供了一些客户端代码来处理数据 URI 字符串(如 base64Image)以正确的格式上传到服务器。