1

我正在为我的 API 使用 Angular6 和 NodeJS。我的应用程序是一个学校软件,我应该用他们的注册号保存学生图像。我在 Angular 中使用ng2-file-upload进行文件上传,在NodeJS中使用 Multer,上传工作正常,但我不明白如何用 Student 的注册号重命名文件我在 Angular 中的网址由学生注册号组成,我只需要知道如何发送该注册号。编号为 NodeJS 并使用 Reg 重命名文件。数字


我的 .html 文件

<input type="file" name="photo" ng2FileSelect [uploader]="uploader" />

<button type="button" class="btn btn-success btn-s" 
  (click)="uploader.uploadAll()" 
  [disabled]="!uploader.getNotUploadedItems().length" >
      Upload an Image
</button>

我的 .ts 文件

public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'file'});
  ngOnInit() {
    this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };
    this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
         console.log('ImageUpload:uploaded:', item, status, response);
         alert('File uploaded successfully');
     };
  }

我的 NodeJS Multer 上传:

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, 'E:/school')
    },
    filename: function (req, file, cb) {
      cb(null, Date.now() + '-' + file.originalname);
    }
  });

  var upload = multer({ storage: storage });

  router.post('/upload', upload.single('file'), (req, res) => {
      if (!req.file) {
        console.log("No file received");
        return res.send({
          success: false
        });

      } else {
        console.log('file received');
        return res.send({
          success: true
        })
      }
  });

提前致谢。任何帮助将不胜感激。

4

3 回答 3

2

您可以在将 formData 发布到后端之前编辑名称。给出文件名(或从表单中获取)并从要上传的文件中获取文件扩展名。然后在发布到后端之前附加到 formData。

参考:https ://stackoverflow.com/a/55178342和https://youtu.be/v67NunIp5w8

  let fileToUpload = <File>files[0];
  let fileName:string = 'test-name' //get name from form for example
  let fileExtension:string = fileToUpload.name.split('?')[0].split('.').pop();

  const formData = new FormData();
  formData.append('file', fileToUpload, fileName+'.'+fileExtension);

  this.http.post(environment.backendApiUrl+'/api/upload', formData, {reportProgress: true, observe: 'events'})
    .subscribe(event => {
      if(event.type === HttpEventType.UploadProgress) {
        this.progress = Math.round(100 * event.loaded / event.total);
      } else if (event.type === HttpEventType.Response) {
        this.message = 'Upload success.';
        this.onUploadFinished.emit(event.body);
      }
    });
于 2020-08-22T07:59:43.120 回答
1

注意:这个解决方案应该可以工作,但是这个代码很难看,可能不是做你想做的最好的方法。但这只是向您展示如何在前端重命名文件。

重要提示:我假设您正在上传单个文件,因为我们将在uploader.queue此示例中使用第一项。

首先,您可以在输入文件下方的 HTML 文件中添加输入类型文本:


<input *ngIf="uploader.queue.length" type="text" name="file" [value]="uploader.queue[0].file.name"
       (change)="renameFile($event.target.value)"/>

当您上传文件时,将显示此输入。将使用当前输入值(change)触发renameFile组件中的函数。

然后通过添加 renameFile 方法更新您的 TS 组件:

renameFile(name: string): void {
    // fetching the item uploaded
    const oldFileItem: FileItem = this.uploader.queue[0];
    // re-instanciating a new file based on the old file by changing the name property
    const newFile: File = new File([this.uploader.queue[0]._file], name, {type: oldFileItem.file.type});
    // uploader.queue is taking FileItem objects, instanciating a new FileItem
    const newFileItem = new FileItem(this.uploader, newFile, this.opts);

    // replacing the old one by the new file updated
    this.uploader.queue[0] = newFileItem;
  }

最后,您可以在函数里面的console.log 中查看文件属性onCompleteItem,该文件已更新。

于 2019-07-26T07:25:35.410 回答
-1

您应该能够观看onFileSelected事件并获取文件[0](如果您是单个文件上传)。并设置file[0].name上传前。

于 2018-10-08T03:31:20.347 回答