【问题标题】:How to fix file upload problem in Angular and NodeJs?如何解决 Angular 和 NodeJs 中的文件上传问题?
【发布时间】:2019-08-29 02:10:57
【问题描述】:

我正在尝试通过网络浏览器上传文件,但我不能这样做。当我通过邮递员保存此 api 然后上传文件但我无法通过尝试网络浏览器上传文件。当我尝试通过网络浏览器上传文件时,我在服务器端收到类似“SyntaxError: Unexpected token - in JSON at position 0”之类的错误。

我使用 NodeJS,ExpressJs 作为后端,Angular 6 作为前端。

角度

html

<div>
  <div>
    <input type="file" (change)="createFormData($event)">
  </div>
  <button (click)="upload()">Upload</button>
</div>

ts

export class PhotographComponent implements OnInit {
  selectedFile: File = null;
  fd = new FormData();

  constructor(private formBuilder: FormBuilder, private httpClient: 
  HttpClient) {}

  ngOnInit() {}

  createFormData(event) {
    this.selectedFile = <File>event.target.files[0];
    this.fd.append('photo', this.selectedFile, this.selectedFile.name);
  }

  upload() {
    this.httpClient.post(environment.apiUrl + 'photographs', this.fd)
      .subscribe( result => {
        console.log(result);
      });
  }

}

NodeJs

const { Photograph, validate } = require('../models/photograph');
const multer  = require('multer');
const express = require('express');
const router = express.Router();

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
})

const upload = multer({
    storage: storage
})

// save photograph
router.post('/', upload.single('photo'), (req, res) => {
    console.log(req.file);
    const filename = req.file.filename;
    const path = req.file.path;

    res.json({message: 'File uploaded'});
})

module.exports = router;

请帮我找到上传文件的解决方案。 谢谢。

【问题讨论】:

  • 这个错误发生在服务器端吗?还有你上传的文件大小是多少?
  • 是的。当我通过邮递员保存此 api 然后上传文件但我无法通过尝试网络浏览器上传文件。当我尝试通过网络浏览器上传文件时,我在服务器端收到类似“SyntaxError: Unexpected token - in JSON at position 0”之类的错误。
  • 我的文件大小只有45kb
  • 您是否尝试过将客户端的请求标头显式设置为enctype: multipart/form-data
  • 不,我没有。我在 Auth Intercepter 中设置了标题('Content-Type': 'application/json')

标签: node.js angular multer


【解决方案1】:

其实我已经找到了我的解决方案。我的后端(NodeJs)代码是正确的。我已经修改了我的前端(Angular)并进行了一些更改。

角度

html

<input id="photo" type="file" />

<button type="button" (click)="upload()">
  Upload
</button>

ts

upload() {
let inputEl: HTMLInputElement = this.el.nativeElement.querySelector('#photo');
console.log("iam+ " + inputEl);
let fileCount: number = inputEl.files.length;
let formData = new FormData();
if (fileCount > 0) { // a file was selected
  for (let i = 0; i < fileCount; i++) {
    formData.append('photo', inputEl.files.item(i));
  }

  this.httpClient.post(URL, formData)
    .subscribe((res) => {
        console.log('Upload Success');
      },
      msg => {
        console.error(`Error: ${msg.status} ${msg.statusText}`);
      }
    );
  }

}

【讨论】:

    【解决方案2】:

    在客户端的请求头中添加'Accept': 'application/json'

    private getHeaders() {
        const headers = new HttpHeaders({
          'Accept': 'application/json',
        });
        return headers;
      }
        upload() {
            this.httpClient.post(environment.apiUrl + 'photographs', this.fd,{ headers: this.getHeaders() })
              .subscribe( result => {
                console.log(result);
              });
          }
    

    在 Nodejs 应用程序中,在中间件的响应标头中添加“Accept”

        app.use((req, res, next) => {
        res.header("Access-Control-Allow-Origin", "*");
        res.header(
            "Access-Control-Allow-Headers",
            "Origin, X-Requested-With, Content-Type, Accept, Authorization, PublicKey"
        );
        next();
    });
    

    【讨论】:

      【解决方案3】:

      您似乎遇到了 httpInterceptor 问题,我也遇到了同样的问题, 您可以覆盖 httpInterceptor 或创建新的 httpClient。

      这可能会对您有所帮助:

      export class PhotographComponent implements OnInit {
        private customHttpClient: HttpClient;
        selectedFile: File = null;
        fd = new FormData();
      
        constructor(private formBuilder: FormBuilder, private httpClient: 
        HttpClient, private handler: HttpBackend) {
           this.customHttpClient = new HttpClient(handler);
        }
      
        ngOnInit() {}
      
        createFormData(event) {
          this.selectedFile = <File>event.target.files[0];
          this.fd.append('photo', this.selectedFile, this.selectedFile.name);
        }
      
        upload() {
           const httpOptions = {
               headers: new HttpHeaders({
               'Accept': 'application/json',
               //'Authorization': 'Bearer '+ token,
             })
           };
      
          this.customHttpClient.post(environment.apiUrl + 'photographs', this.fd, httpOptions )
            .subscribe( result => {
              console.log(result);
            });
        }
      
      }
      

      【讨论】:

      • 不客气,你能检查一下这个方法是否有效吗?也谢谢你。
      猜你喜欢
      • 2021-04-17
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 2021-06-27
      • 2018-01-02
      • 2019-06-19
      • 2011-08-20
      相关资源
      最近更新 更多