簡體   English   中英

在將文件追加到FormData中后無法上傳文件

[英]can't upload file after appending it to FormData in angular

我正在嘗試將請求后的文件發送到我的后端,它的響應狀態為500 cuz,請求中沒有文件->在檢查出我的formData為空並且不包含任何文件后,請求響應。

這是我的功能:

  createProductsByCsv(): void {
const self = this;
  const setting: any = {
    title: '<h5>Add Products By CSV file</h5>',
    html:
      '<div class="form-group row">\n' +
      '   <label class="col-sm-4 col-form-label">File</label>\n' +
      '       <div class="col-sm-8">\n' + '<input type="file" accept=".csv" name="csv-file" id="csv-file" class="form-control datepicker" placeholder="chose csv file">' +
      '       </div>\n' +
      '</div>',
    confirmButtonText: 'add the file',
    focusConfirm: false,
    showLoaderOnConfirm: true
  };

  setting.preConfirm = (text) => {
    var file = $('#csv-file').prop('files')[0];
    // console.log(file);

    var formData = new FormData();
    formData.append('file', file, file.name);
    console.log(formData);

    if(((file.name.split(".").length -1) > 1) && (file.name.endswith('.csv'))) 
      return self.sweetAlert.error({title: 'Error', text: "Upload only files that ends with .csv and containe single dot otherwise it will be ignored !"});
    else 
    return self.httpApi.post('/catalog/product/filetest',formData).toPromise()
      .then(resp => {
        if (resp.status == 200) {
          self.sweetAlert.success({title: 'Success', text: JSON.stringify(resp.message )});
        } else {
          self.sweetAlert.error({title: 'Error', text: JSON.stringify(resp.message )});
        }
      })
      .catch(msg => console.log('ERROR' + msg.message + ' ' + msg.message));
  };
  swal.queue([setting]); }

難道我做錯了什么 ?

嘗試這樣:

.html

<input #fileInput type="file" accept=".csv" name="csv-file" id="csv-file" class="form-control datepicker" placeholder="chose csv file">

<button  (click)="saveFile(fileInput)">Upload</button>

.ts

 saveFile(fileInput) {
    let fi = fileInput;

    if (fi.files && fi.files[0]) {
      let fileToUpload = fi.files[0];

      let formData: FormData = new FormData();
      formData.append("file", fileToUpload);

      console.log(formData);
      ...
      // http call
    }
  }

我剛剛測試了這段代碼,當將文件發布到laravel后端時,它可以正常工作。

我認為您的問題出在后端,而不是在前端,請檢查您的后端Controller / Middleware函數是否接受“ multipart / form-data

import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  @ViewChild('fileInput', {static: true}) fileInput: ElementRef;

  constructor(
      private httpclient: HttpClient
  ) {}

  ngOnInit(): void {
  }

  testUpload() {
    if (!this.fileInput.nativeElement.files.length) {
      console.log('there is no file to upload');
      return;
    }
    const data = new FormData();
    data.append('testFile', this.fileInput.nativeElement.files[0], this.fileInput.nativeElement.files[0].name);

    this.httpclient.post('http://localhost:8000/api/upload/test', data).subscribe((res: Response) => {
      console.log(res);
    });
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM