文件未从Angular发送到Node.js [英] File not sending from Angular to Nodejs

查看:95
本文介绍了文件未从Angular发送到Node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用

后端输出

 文件上传部分{文件:{},文件名:'image.png'} 

但是从控制台输出可以看到,当在后端接收时为空.不知道为什么.感谢您的帮助!

file-picker.adapter.ts

  import'FilePreviewModel}从'ngx-awesome-uploader';从'@ angular/common/http'导入{HttpRequest,HttpClient,HttpEvent,HttpEventType};从'rxjs/operators'导入{map};从"rxjs"导入{Observable};从'ngx-awesome-uploader'导入{FilePickerAdapter};从'./file-upload.model'导入{FilePreviewModelWithAuctionId};从'src/environments/environment'导入{环境};导出类DemoFilePickerAdapter {构造函数(私有http:HttpClient){}公共uploadFile(fileItem:FilePreviewModel){const form = new FormData();form.append('file',fileItem.file);console.log(文件输出");console.log(fileItem.file);const api = environment.api_url +"/fileupload";const req = new HttpRequest('POST',api,fileItem,{reportProgress:true});返回this.http.request(req).管道(map((res:HttpEvent< any>)=> {如果(res.type === HttpEventType.Response){返回res.body.id.toString();}否则,如果(res.type === HttpEventType.UploadProgress){//计算并显示完成百分比:const UploadProgress = + Math.round((100 * res.loaded)/res.total);返回UploadProgress;}}));}} 

app.js

  app.post("/api/fileupload",checkAuth,(req,res,next)=> {console.log(文件上传部分")console.log(要求正文)blobService.createContainerIfNotExists('testcontainer',{publicAccessLevel:"blob"},函数(错误,结果,响应){如果(!错误){//如果result = true,则创建容器.//如果result = false,则表明容器已经存在.}});blobService.createBlockBlobFromLocalFile('testcontainer','taskblob',req.body.file,function(error,result,response){如果(!错误){//上传的文件}});}); 

FilePreviewModel

 导出接口FilePreviewModel {fileId ?:字符串;文件:文件|Blob;fileName:字符串;} 

FilePreviewModelWithAuctionId

 导出接口FilePreviewModelWithAuctionId {fileId ?:字符串;文件:文件|Blob;fileName:字符串;AuctionId:字符串;} 

解决方案

由于这个原因,您忘记了指定内容类型,所以找不到文件.

将此标头添加到您的请求中.

  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); 


更新:

我没看到您也缺少服务器中的multipart/form-data处理程序.

请按照以下步骤操作:

npm install-保存multer

在您的nodejs应用中导入multer:

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

修改端点:

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

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;
}

解决方案

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);
...
}

这篇关于文件未从Angular发送到Node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆