使用带有角度7的均值堆栈的multer中间件上传文件

时间:2019-12-05 19:46:44

标签: angular express multer

请,我正在使用multer中间件以角度均值堆栈上传文件。我无法获取req.file,但可以获取req.body,这意味着该文件未上传。 首先,当我上传时,我检查了指定的上传文件夹,除了其他文本数据可以进入猫鼬数据库,我什么都看不到。

然后我尝试重新发送(req.file.filename),它说找不到未定义的属性'filename'。当我重新发送(req.file)时,它返回null。但是当我重新发送(req.body)时,它返回从html表单键入的文本数据。我做错了什么?

我在stackoverflow和其他在线位置上针对类似问题已经提出了许多建议,但没有一个能为我解决问题。

请帮助

在下面的vehicle.route.js中找到我的代码:

  path = require('path'),
  multer = require('multer'),

  app = express();

  const DIR = '../uploads/';
  const storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, DIR);
    },
    filename: (req, file, cb) => {
      const fileName = file.fieldname + '-' + Date.now();
      cb(null, fileName)
    }
  });

  let upload = multer({ 
    storage: storage
  })

vehicleRouter = express.Router();

// Vehicle model
let Vehicle = require('../models/Vehicle');

app.use(express.static(path.join(__dirname, '../uploads')));


// Get All Employees
vehicleRouter.route('/').get((req, res, next) => {
  Vehicle.find((error, data) => {
    if (error) {
      return next(error)
    } else {
      res.json(data)
    }
  })
})



vehicleRouter.post('/register', upload.single('purchaseReceipt'), (req, res, next) => {
  res.json(req.file.filename)
  return;

/*vehicleRouter.post('/register', upload.single('purchaseReceipt'), (req, res, next) => {
  res.json(req.file)
  return;
  const vehicle = new Vehicle({
    fullName: req.body.fullName,
    purchaseReceipt: req.file.filename
  });
  vehicle.save().then(result => {
    console.log(result);
    res.status(201).json({
      message: "Vehicle registered successfully!",
      userCreated: {
        _id: result._id,
        name: result.name,
        purchaseReceipt: result.purchaseReceipt
      }
    })
  })

  /*Vehicle.create(req.body, (error, data) => {
    if (error) {
      return next(error)
    } else {
      res.json(data)
    }
  })*/

  //res.json('from register vehicle')
  })

  app.use(express.static(path.join(__dirname, './uploads')));
module.exports = vehicleRouter;```

I tried uploading straight but it isnt then I commented part of the code and tried to send back req.file.filename as response but it is saying: error: "Cannot read property 'filename' of undefined"

[the error code on console][1]


  [1]: https://i.stack.imgur.com/LY9ob.png


vehicle-registration.component.html code ie the html form
```<div class="card">
  <div class="card-body">
    <form method="post" [formGroup]="vehicleForm" (ngSubmit)="onSubmit()" enctype="multipart/form-data">
      <div class="form-group">
        <label class="col-md-4">Full Name</label>
        <input type="text" class="form-control" formControlName="fullName" />
      </div>

      <div class="form-group">
        <div class="preview" *ngIf="preview && preview !== null">
          <img [src]="preview" [alt]="vehicleForm.value.name">
        </div>
      </div>

      <!--<div class="form-group">
        <label class="col-md-4">Upload Purchase Receipt</label>
        <input type="text" class="form-control" formControlName="purchaseReceipt" />
      </div>-->
      <div class="form-group">
        <label class="col-md-4">Upload Purchase Receipt </label>
        <input type="file" class="form-control"  (change)="uploadFile($event)" formControlName="purchaseReceipt" name="purchaseReceipt"/>
      </div>

      <div class="form-group">
        <div class="row">
          <div class="col-sm-3">
              <button class="btn btn-success btn-sm btn-block" type="submit">Register Vehicle</button>
          </div>
        </div>
        </div>

    </form>
  </div>
</div>```


vehicle-registration.component.ts code

从'@ angular / core'导入{Component,OnInit}; 从'@ angular / forms'导入{FormGroup,FormBuilder,Validators}; 从“ ../../service/vehicle.service”导入{VehicleService};

@Component({   选择器:“ app-vehicle-registration”,   templateUrl:“ ./ vehicle-registration.component.html”,   styleUrls:['./ vehicle-registration.component.css'] }) 出口类VehicleRegistrationComponent实现OnInit {   预览:字符串;   vehicleForm:FormGroup;

构造函数(公共fb:FormBuilder,私有vs:VehicleService){     this.createForm()   }

ngOnInit(){   }

createForm(){     this.vehicleForm = this.fb.group({      fullName:['',[Validators.required]],      PurchaseReceipt:[null,[Validators.required]],     });   }

uploadFile(event){     const file =(event.target as HTMLInputElement).files [0];     this.vehicleForm.patchValue({       头像:文件     });     this.vehicleForm.get('avatar')     // .updateValueAndValidity()

// File Preview
const reader = new FileReader();
reader.onload = () => {
  this.preview = reader.result as string;
}
reader.readAsDataURL(file)

}

onSubmit(){     如果(!this.vehicleForm.valid){       返回false;     }其他{       this.vs.registerVehicle(this.vehicleForm.value)        。订阅(          (res)=> {          console.log('车辆成功注册!');          console.log(res);          },          (错误)=> {            console.log(错误);          }        );     }   }

}```

服务文件,即vehicle.service.ts

import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';


@Injectable({
  providedIn: 'root'
})
export class VehicleService {

  baseUri: string = 'http://localhost:3000/vehicle';
  headers = new HttpHeaders().set('Content-Type', 'application/json');

  constructor(private http: HttpClient) { }

  registerVehicle(data): Observable<any>{
    console.log(data);
    const url = `${this.baseUri}/register`;
    return this.http.post(url, data);
  }

}```

1 个答案:

答案 0 :(得分:0)

您好,您可以发布角度代码,以便我们查看您是否实际上是在将文件发送到后端-nodejs。谢谢,等待中

新更新!

抱歉,我弄错了智慧。我应该设置表格数据 在您使用的地方使用formdata.set ....

let image = new fileReader();
formdata: Formdata = new Formdata();  //updated!!

constructor(){}

preview($event){
this.image.onloadend = ()=>{
    //other codes
    this.formdata.set("image", $event.target.files[0]); // you can use this.formdata.append(...) if you want, but append keeps adding if maybe there is a retry due to error
}

this.image.readAsDataURL($event.target.files[0]);

}





onsubmit(){


//append or set other thing

this.vs.registerVehicle(this.formdata).subscribe(d=>{
// code here
})


}



在上传图片时使用formData可以更轻松地在后端接收文件。