简体   繁体   English

Angular6 重命名要上传的文件

[英]Angular6 Rename the File to be Uploaded

I am using Angular6 and NodeJS for my API.我的 API 使用 Angular6 和 NodeJS。 MY application is a School Software where I should save Students Images with their Registration Numbers.我的应用程序是一个学校软件,我应该在其中保存学生图像及其注册号。 I am using ng2-file-upload in Angular for File Uploads and Multer in NodeJS, Upload is working perfectly, but I can't understand how to rename the file with the registration number of Student .我在 Angular 中使用ng2-file-upload进行文件上传,在NodeJS中使用Multer ,上传工作正常,但我无法理解如何使用 Student 的注册号重命名文件 My url in Angular consists of Student Registration number , I just need to know how to send that Reg.我在 Angular 中的 url 由 Student Registration number 组成,我只需要知道如何发送那个 Reg。 Number to NodeJS and rename the file with Reg.编号到 NodeJS 并使用 Reg 重命名文件。 Number数字


My html File我的 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>

My .ts file我的 .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');
     };
  }

My NodeJS Multer Upload:我的 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
        })
      }
  });

Thanks in Advance.提前致谢。 Any help will be Appreciated.任何帮助将不胜感激。

Be careful : This solution should work however this code is ugly and probably not the best way to do what you want.小心:这个解决方案应该可以工作,但是这段代码很丑陋,可能不是做你想做的最好的方法。 But it's just to show you how you can rename your file in the front-end side.但这只是为了向您展示如何在前端重命名文件。

Important: I will assume you are uploading a single file because we will use the first item of the uploader.queue for this example.重要提示:我假设您上传的是单个文件,因为我们将在本示例中使用uploader.queue的第一项。

First, you can add an input type text in your HTML file just below your input file :首先,您可以在输入文件正下方的 HTML 文件中添加输入类型文本:


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

This input will be showed when you will upload a file.当您上传文件时,将显示此输入。 The (change) will trigger the renameFile func in your component with the current input value. (change)将使用当前输入值触发组件中的renameFile函数。

Then update your TS component by adding the renameFile method :然后通过添加 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;
  }

Finally, you can have a look to the file property in your console.log inside the onCompleteItem function, the file has been updated.最后,您可以在onCompleteItem函数内的 console.log 中查看文件属性,该文件已更新。

You can edit the name before posting the formData to the backend.您可以在将 formData 发布到后端之前编辑名称。 Give the file name (or get from a form) and get the file extension from the file to upload.提供文件名(或从表单中获取)并从要上传的文件中获取文件扩展名。 Then append to formData before posting to the backend.然后在发布到后端之前附加到 formData 。

Reference: https://stackoverflow.com/a/55178342 and https://youtu.be/v67NunIp5w8参考: https : //stackoverflow.com/a/55178342https://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);
      }
    });

You should be able to watch the onFileSelected event and get file[0] (if you are single file upload).您应该能够观看onFileSelected事件并获取 file[0] (如果您是单个文件上传)。 And set the file[0].name before uploading.并在上传前设置file[0].name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM