Angular NodeJs multer上传img req.file始终未定义

时间:2018-10-31 16:45:11

标签: mysql node.js angular express

我将req.file设为未定义。我已经尝试了一切。我已经搜索了其他解决方案,但是在输入name =“ avatar” attr和upload.single("avatar")中没有问题。

此外,我在控制台中遇到错误:

Error for image upload 400 - Bad Request
{"code":"ER_PARSE_ERROR","errno":1064,"sqlMessage":"You have an error
in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near '?)' at line
1","sqlState":"42000","index":0,"sql":"INSERT INTO avatars (image)
VALUES(?)"}

我会说这是因为req.file是未定义的。 请帮我了解我在做什么错。

api.js:

var storage = multer.diskStorage({
destination: function(req, file, callback) {
  callback(null, "./assets/images/uploads");
},
filename: function(req, file, callback) {
  callback(null, file.fieldname + "_" + Date.now() + "_" + 
  file.originalname);
  }
});

var upload = multer({
  storage: storage,
  limits: {fileSize: 1000000},
  fileFilter: function(req, file, cb) {
    checkFileType(file, cb);
  }
});

function checkFileType(file, cb) {
  const filetypes = /jpeg|jpg|png|gif/;
  const extname = filetypes.test(file.originalname.toLowerCase());
  const mimetype = filetypes.test(file.mimetype);

  if(extname && mimetype) {
    return cb(null, true);
   } else {
     cb('Error: Images only');
   }
 }

 router.post("/upload", upload.single('avatar'), function(req, res) {
   console.log(req.file); // <- ALWAYS UNDEFINED

   pool.getConnection(function(err, connection) {
     if (err) throw err;

   connection.query('INSERT INTO avatars (image) VALUES(?)', req.file, 
     function (error, results, fields) {
    if(error){
      console.log("Error: " + error);
      res.status(400).send(error);
    }
    res.status(200).end(JSON.stringify(results));
    connection.release();
    if (error) throw error;
    });
  });
});

html:

 <form enctype="multipart/form-data">
  <input  class="form-control"
          (change)="onFileSelected($event)"
          type="file" name="avatar">
  <button type="submit" class="btn btn-danger float-right" (click)="onUpload()">Upload image</button>
</form>

ctrl:

onFileSelected(event) {
  if(event.target.files.length > 0) {
    this.uploadImage = <File>event.target.files[0];
  }
}

onUpload() {
  if(this.uploadImage) {
    this.friendService.uploadFile(this.uploadImage)
      .subscribe(
        data => {
          return true;
        },
        error => {
          console.error('Error for image upload ' + error);
          return false;
        })
  }
}

服务:

   uploadFile(file): Observable<any> {
     return this.http.post(`${this.apiUrl}/upload`, file)
     .map(res => res.json())
     .catch(this.handleError);
   }

db mysql头像表:

     Field                - image   
     Type                 - blob    
     Null                 - NO 
     Key Default    Extra - Empty

1 个答案:

答案 0 :(得分:0)

上传文件时,文件应为表单数据,内容类型应为多部分/表单数据

供参考:File Upload In Angular?

我希望这会对您有所帮助。