【问题标题】:upload and download of file in angular 2?以角度2上传和下载文件?
【发布时间】:2017-04-13 19:52:20
【问题描述】:

我正在使用 Angular2、TypeScript 将文件连同 JSON 数据一起发送到服务器。

HTML代码

 <input type="file" class="form-control" name="avatar"   id="uploadyour" name="uploadyour"   #uploadyour="ngModel"  [(ngModel)]="model.uploadyour"  
           (change)="fileChange($event)"  placeholder="Upload file" accept=".pdf,.doc,.docx" >

app.component.ts.

import { Http, Headers, Response, Request, RequestMethod, URLSearchParams, RequestOptions } from "@angular/http";
import * as FileSaver from "file-saver";
import {Observable} from 'rxjs/Rx';
import { Injectable } from '@angular/core';

fileChange(event) { 
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {

        let file: File = fileList[0];
        let formData:FormData = new FormData();
        console.log(file);
        formData.append('uploadFile', file, file.name);
        let headers = new Headers();
        headers.append('enctype', 'multipart/form-data');
        headers.append('Accept', 'application/json');
        console.log(headers);
        let options = new RequestOptions({ headers: headers });
        console.log(formData);
        this.http.post("http://localhost:1337/trackstatus/upload", formData, options)
            .map(res => res.json())
            .catch(error => Observable.throw(error))
            .subscribe(
                data => console.log('success'),
                error => console.log(error)

            )
        }

    }



controller.js

upload: function  (req, res) {
     req.file('avatar').upload(function (err, files) {
      if (err)
        return res.serverError(err);

      return res.json({

        message: files.length + ' file(s) uploaded successfully!',

        files: files

                });
            });



        },

我遇到了错误。

XMLHttpRequest 无法加载 http://localhost:1337/trackstatus/upload。预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 enctype。

【问题讨论】:

标签: angular sails.js


【解决方案1】:

您需要更新服务器上的设置以允许来自运行 Angular 代码的域的 AJAX 请求。如果您的 Angular 应用程序已在某处发布,则这可能是 localhost 或其他域。如何更改 CORS 设置的具体细节取决于您的服务器端堆栈,但这个 SO 答案显示了一般修复:

https://stackoverflow.com/a/10143166/571237

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-21
    • 2017-02-23
    • 2021-12-22
    • 1970-01-01
    • 2017-01-10
    • 2015-10-02
    • 2021-01-29
    • 2021-11-27
    相关资源
    最近更新 更多