简体   繁体   中英

upload and download of file in angular 2?

I'm using Angular2, TypeScript to send a file, along with JSON Data to a server.

Html code

 <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

                });
            });



        },

I am getting below error.

XMLHttpRequest cannot load http://localhost:1337/trackstatus/upload . Request header field enctype is not allowed by Access-Control-Allow-Headers in preflight response.

You need to update the settings on your server to allow AJAX requests from the domain that your Angular code is running on. This could be localhost or some other domain if your Angular app is already published somewhere. The specifics of how to change the CORS settings depends on your server side stack, but this SO answer shows the general fix:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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