使用表单数据上传angular 2文件

时间:2017-12-20 11:19:03

标签: javascript jquery django angular angular-file-upload

我想在angular2项目中实现文件上传功能。我想限制用户仅上传特定类型的文件:.pdf.doc.docx

以下是我的fileChange代码:

  fileChange(event) {
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
      let file: File = fileList[0];
      console.log('file',file);

      var formData = new FormData();
      formData.append('file', file, file.name);
      var options = { content: formData };

      console.log('options',options);
      var jsonBody = {};
      jsonBody['submoduleid'] = '3789e76489fc4e118f8dffad107fbbbd';
      jsonBody['file'] = options;
      console.log('jsonbody',jsonBody);

      this.Module7Service.uploadFile(jsonBody) 
      .subscribe(
        data => {
          console.log(data.Response)
          if (data.message == "module7 finish") {
            console.log('after success',jsonBody)
            alert('done file uploaded successfully');
          }
          else{
            alert('not uploaded');
          }
      });
    }
  }

以下是我的uploadFile代码:

  //service code
  uploadFile(file){
    const body = file;
    const headers = new Headers({
      'Authorization': window.localStorage.getItem('token'),
      'content_type' : 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW',
      'Accept': 'application/json',
      'Access-Control-Allow-Origin' : '*',
      'Access-Control-Allow-Credentials': 'true',
      'Access-Control-Allow-Methods': 'GET,HEAD,OPTIONS,POST,PUT',
      'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
      'Source': 'WEB'
    });
    return this.http.post(this.apiUrl + 'module7/', { body: body }, { headers: headers })
      .map(
      res => {
        return res.json();
      },
      error => alert("आपली विनंती आत्ता पूर्ण करू शकत नाही, कृपया पुन्हा प्रयत्न करा."));
  }

这是input HTML标记:

<input type="file" (change)="fileChange($event)"
       placeholder="Upload file" accept=".pdf,.doc,.docx">

我添加了所有必需的密钥,formdata等,但是当我上传文件时出现了一些错误:

  

XMLHttpRequest无法加载“apiurl”。在预检响应中,Access-Control-Allow-Header不允许使用请求标题字段Access-Control-Allow-Methods。

Here是浏览器控制台中错误的图像。

这个问题可能是什么来源?

0 个答案:

没有答案