File not sending from Angular to Nodejs

廉价感情. 提交于 2021-01-27 14:33:44

问题


I'm using an ngx-awesome-uploader to add my images to angular to send to backend. I'm trying to send the file to my nodejs backend, but it keeps returning {} on backend where the file should be. Never worked with files before, but I'm gonna take an educated guess and say that should have something in there.

On the frontend it looks like the file is there to be sent because console.log(fileUpload.file);

output

BACKEND OUTPUT

File Upload Section
{ file: {}, fileName: 'image.png' }

But is empty when received on the backend side as you can see from console output. Not sure why. I appreciate the help!

file-picker.adapter.ts

import { FilePreviewModel } from 'ngx-awesome-uploader';
import { HttpRequest, HttpClient, HttpEvent, HttpEventType } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { FilePickerAdapter } from 'ngx-awesome-uploader';
import { FilePreviewModelWithAuctionId } from './file-upload.model';
import { environment } from 'src/environments/environment';

export class DemoFilePickerAdapter {
  constructor(private http: HttpClient) {
  }
  public uploadFile(fileItem: FilePreviewModel) {
    const form = new FormData();
    form.append('file', fileItem.file);

    console.log("FILE OUTPUT");
    console.log(fileItem.file);

    const api = environment.api_url + "/fileupload";
    const req = new HttpRequest('POST', api, fileItem, { reportProgress: true });
    return this.http.request(req)
      .pipe(
        map((res: HttpEvent<any>) => {
          if (res.type === HttpEventType.Response) {
            return res.body.id.toString();
          } else if (res.type === HttpEventType.UploadProgress) {
            // Compute and show the % done:
            const UploadProgress = +Math.round((100 * res.loaded) / res.total);
            return UploadProgress;
          }
        })
      );


  }

}

app.js

app.post("/api/fileupload", checkAuth, (req, res, next) => {

  console.log("File Upload Section")
  console.log(req.body)


  blobService.createContainerIfNotExists('testcontainer', {
    publicAccessLevel: 'blob'
  }, function (error, result, response) {
    if (!error) {
      // if result = true, container was created.
      // if result = false, container already existed.
    }
  });

  blobService.createBlockBlobFromLocalFile('testcontainer', 'taskblob', req.body.file, function (error, result, response) {
    if (!error) {
      // file uploaded
    }
  });



});

FilePreviewModel

export interface FilePreviewModel {
    fileId?: string;
    file: File | Blob;
    fileName: string;
}

FilePreviewModelWithAuctionId

export interface FilePreviewModelWithAuctionId {
  fileId?: string;
  file: File | Blob;
  fileName: string;
  auctionId: string;
}


回答1:


You forgot to specify the content type for this reason you cannot find the file.

Add this header to your request.

let headers = new HttpHeaders();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
let options = { headers: headers, reportProgress: true  };

const api = environment.api_url + "/fileupload";
const req = new HttpRequest('POST', api, form , options );

Update :

I didn't see you are missing the handler for multipart/form-data in your server too.

Follow these steps:

npm install --save multer

import multer in your nodejs app :

const multer = require('multer');
const upload = multer({dest: 'public/uploads/'}).single('file');

Modify your endpoint :

app.post("/api/fileupload", checkAuth, upload, (req, res, next) => {
console.log(req.file);
...
}



回答2:


You've declared a form but it's never being in use. Try the following:

import { FilePreviewModel } from 'ngx-awesome-uploader';
import { HttpRequest, HttpClient, HttpEvent, HttpEventType } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { FilePickerAdapter } from 'ngx-awesome-uploader';
import { FilePreviewModelWithAuctionId } from './file-upload.model';
import { environment } from 'src/environments/environment';

export class DemoFilePickerAdapter {
  constructor(private http: HttpClient) {
  }
  public uploadFile(fileItem: FilePreviewModel) {
    let form = new FormData();
    form.append('file', fileItem.file);

    console.log("FILE OUTPUT");
    console.log(fileItem.file);

    const api = environment.api_url + "/fileupload";
    const req = new HttpRequest('POST', api, form , { reportProgress: true });
    return this.http.request(req)
      .pipe(
        map((res: HttpEvent<any>) => {
          if (res.type === HttpEventType.Response) {
            return res.body.id.toString();
          } else if (res.type === HttpEventType.UploadProgress) {
            // Compute and show the % done:
            const UploadProgress = +Math.round((100 * res.loaded) / res.total);
            return UploadProgress;
          }
        })
      );


  }

}


来源:https://stackoverflow.com/questions/60213312/file-not-sending-from-angular-to-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!