繁体   English   中英

multer 和 node/express 文件上传不适用于 Angular

[英]multer and node/express file upload not working with Angular

我正在尝试使用 multer 进行单个文件上传。 虽然我可以使用邮递员等工具在相关文件夹中手动上传文件以测试快速路由,但我无法使用 Angular 前端上传文件。 我在应该上传文件的节点后端文件夹中创建了一个名为 uploads 的文件夹。 此外,我需要在表单中上传文件并将其传递给 api,在那里它也应该将文件与其他参数一起使用。 但不幸的是,它在浏览器控制台上返回状态 500 和内部服务器错误,而在我的节点终端上它返回无法读取未定义的属性“路径”。

我的工作正常的节点后端代码如下:

const multer = require('multer')

const storage = multer.diskStorage({

destination: function(req, file, cb) {

cb(null, './uploads/')

},

filename: function(req, file, cb) {

cb(null, Date.now() + file.originalname)

}

})

const upload = multer({storage: storage})

let baseUrl = appConfig.apiVersion+'/blogs';

app.post(baseUrl+'/create', upload.single('imagePath'), (req, res) => {
    var today = time.now()
    let blogId = shortid.generate()

    let newBlog = new BlogModel({

        blogId: blogId,
        title: req.body.title,
        description: req.body.description,
        bodyHtml: req.body.blogBody,
        isPublished: true,
        category: req.body.category,
        author: req.body.fullName,
        created: today,
        lastModified: today,
        imagePath: req.file.path    //node console is pointing towards this point
    }) // end new blog model

    let tags = (req.body.tags != undefined && req.body.tags != null && req.body.tags != '') ? req.body.tags.split(',') : []
    newBlog.tags = tags

    newBlog.save((err, result) => {
        if (err) {
            console.log(err)
            res.send(err)
        } else {
            res.send(result)

        }
    }) // end new blog save
});

下面是我的 Angular 组件代码,它不起作用:

selectImage(event) {
    if(event.target.files.length > 0){
      const file = event.target.files[0];
      this.images = file;
    }
  }

  public createBlog(): any {

    const formData = new FormData();
    const form = formData.append('imagePath', this.images);


    let blogData = {
      title: this.blogTitle,
      description: this.blogDescription,
      blogBody: this.blogBodyHtml,
      category: this.blogCategory,
      imagePath: form 
    } //end blogData

    console.log(blogData);

    this.blogHttpService.createBlog(blogData).subscribe(

      data => {
        console.log(data);
        this.toastr.successToastr('Blog Posted Susseccfully!', 'Success!');
        setTimeout(() =>{
          this.router.navigate(['blog', data.blogId]);
        }, 1000)

      },

      error => {
        console.log(error);
        console.log(error.errorMessage);
        this.toastr.errorToastr('This is not good!', 'Oops!');
      })
  }

角度服务代码

public createBlog(blogData): any {
    let myResponse = this._http.post(this.baseUrl + '/create', blogData);
    return myResponse;

  }

前端 HTML 代码:

<div>

<input type="file" name="imagePath" (change)="selectImage($event)" />

</div>

您似乎创建了一个formData对象,但实际上并没有对它做任何事情。 正如您在此处看到的,您正在构建一个对象并将其与您的请求一起发送,但它不包含您的formData

let blogData = {
      title: this.blogTitle,
      description: this.blogDescription,
      blogBody: this.blogBodyHtml,
      category: this.blogCategory,
      imagePath: this.imagePath
    } //end blogData

    console.log(blogData);

    this.blogHttpService.createBlog(blogData).subscribe(

不完全确定您的情况的确切语法是什么,但在这里您可以看到我在我的一个项目中拥有的一些示例代码,希望能给您一个想法。

changeHandler(e) {
    const fd = new FormData();
    fd.append('sample', e.target.files[0]);
    axios.post('/save-image', fd).then(i => {
      this.setState({img: i.data.filename});
    });
  }

如您所见, formData是我实际发送到服务器的内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM