如何以角度2上传文件

时间:2017-08-23 04:14:22

标签: angular2-forms

这是我用来上传文件的功能但却给我错误:长度未定义。我必须在此代码中更改。在哪里提供要上传的文件路径。

fileChange(event) {
        let fileList: FileList = event.target.files;
        if(fileList) {
            let file: File = fileList[0];
            let formData:FormData = new FormData();
            formData.append('uploadFile', file, file.name);
            let headers = new Headers();
            /** No need to include Content-Type in Angular 4 */
            headers.append('Content-Type', 'multipart/form-data');
            headers.append('Accept', 'application/json');
            let options = new RequestOptions({ headers: headers });
            this.http.post(`assets/Files/info.txt`, formData, options)
                .map(res => res.json())
                .catch(error => Observable.throw(error))
                .subscribe(
                    data => console.log(fileList),
                    error => console.log(error)
                )
             }
          }

2 个答案:

答案 0 :(得分:0)

您需要使用xhr请求传输文件

fileChange(event: EventTarget) {
    let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
    let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
    let files: FileList = target.files;
    if(files) {
        let file: File = files[0];
        this.upload(file) 
      }
}
public upload(filedata: File) {
    let url = 'your url'
    if (typeof filedata != 'undefined') {
        return new Promise((resolve, reject) => {
            let formData: any = new FormData();
            let xhr = new XMLHttpRequest();
            formData.append('icondata', filedata, filedata.name);
            xhr.open('POST', url, true);
            xhr.setRequestHeader('Authorization', 'JWT ' + localStorage.getItem('id_token'));
            xhr.send(formData);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == XMLHttpRequest.DONE) {
                    resolve(JSON.parse(xhr.responseText));
                }
            }
        });

    }
}

答案 1 :(得分:0)

我知道这不是你想要的功能但是没有后端你不能上传文件是持久的,它们应该存储在某个地方。例如,如果您只是想操纵文件名,请跳过我的答案中的快速部分。我个人使用这个代码,我改变了上传多个文件。

组件

import {FormArray, FormBuilder, FormControl, FormGroup} from "@angular/forms";

在构造函数中声明FormBuilder:

constructor (private http: Http, private fb: FormBuilder) {}
<{1>}在ngOnInit()中设置变量如下:

this.myForm = this.fb.group({chosenfiles: this.fb.array([])});

这是上传方法的代码:

// invoke the upload to server method
// TODO
// Should be in a service (injectable)
    upload() {
        const formData: any = new FormData();
        const files: Array<File> = this.filesToUpload;
        //console.log(files);
        const chosenf = <FormArray> this.myForm.controls["chosenfiles"];
        // iterate over the number of files
        for(let i =0; i < files.length; i++){
            formData.append("uploads[]", files[i], files[i]['name']);
            // store file name in an array
            chosenf.push(new FormControl(files[i]['name']));
        }
        this.http.post('http://localhost:3003/api/upload', formData)
            .map(files => files.json())
            .subscribe(files => console.log('upload completed, files are : ', files));
    }

负责文件更改的方法:

fileChangeEvent(fileInput: any) {
    this.filesToUpload = <Array<File>>fileInput.target.files;
    const formData: any = new FormData();
    const files: Array<File> = this.filesToUpload;
    console.log(files);
    const chosenf = <FormArray> this.myForm.controls["chosenfiles"];
    // iterate over the number of files
    for(let i =0; i < files.length; i++){
        formData.append("uploads[]", files[i], files[i]['name']);
        // store file name in an array
        chosenf.push(new FormControl(files[i]['name']));
    }
}

模板是这样的

<input id="cin" name="cin" type="file" (change)="fileChangeEvent($event)" placeholder="Upload ..." multiple/>

注意多重负责允许多项选择

处理请求的express API在npm安装后使用 multer

var multer = require('multer');
var path = require('path');

指定一个包含文件的静态目录

// specify the folder
app.use(express.static(path.join(__dirname, 'uploads')));

multer

指定

PS:我没有调查过multer,一旦我开始工作,我就转移到另一个任务但随意删除不必要的代码。

var storage = multer.diskStorage({
  // destination
  destination: function (req, file, cb) {
    cb(null, './uploads/')
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname);
  }
});

var upload = multer({ storage: storage });

最后是终点

app.post("/api/upload", upload.array("uploads[]", 12), function (req, res) {
  console.log('files', req.files);
  res.send(req.files);
});