【问题标题】:Angular 2 - How to upload file and store in local folderAngular 2 - 如何上传文件并存储在本地文件夹中
【发布时间】:2017-09-24 20:48:34
【问题描述】:

例如,我在 src 文件夹下创建了一个名为“upload”的文件夹。

html 文件:

<div>
   <input type="file" id="photo" (change)="onChange($event)" />
</div>
<div class="col-md-6 mb-4 mt-3">
   <button (click)="upload()" class="btn btn-primary w-100">Upload Picture</button>
</div>

上传-modal.component.ts 文件

import { Http, Response } from '@angular/http';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import "rxjs/add/operator/do";
import "rxjs/add/operator/map";
const uploadURL = '/upload';

@Component({

selector: 'upload-modal',
templateUrl: './upload-modal.component.html',
styleUrls: ['./upload-modal.component.css']
})
export class UploadModalComponent {
displayMessage: string = '';
constructor(public activeModal: NgbActiveModal, private http: Http, private el: ElementRef) { }
setDisplayMessage(msg: string) {
   this.displayMessage = msg;
 }

upload() {
   this.activeModal.dismiss('Cross click');
 }

onChange(event) {
 let inputEl: HTMLInputElement = this.el.nativeElement.querySelector('#photo');

let fileCount: number = inputEl.files.length;

let formData = new FormData();

if (fileCount > 0) { // a file was selected

  formData.append('photo', inputEl.files.item(0));

  this.http
    .post(uploadURL, formData).map((res: Response) => res.json()).subscribe(
    // map the success function and alert the response
    (success) => {
      alert("success");
    },
    (error) => alert("error"));
   }

  }
}

当我点击上传按钮时,我在控制台日志中发现了这个错误= http://localhost:3000/upload 404 (Not Found)
我想这必须与路由有关。有人有过经验吗?

【问题讨论】:

    标签: angular file-upload


    【解决方案1】:

    希望这会有所帮助:完整的代码。

    你需要运行这个 cmd:npm i ng2-file-upload --save

    代码:https://github.com/valor-software/ng2-file-upload

    演示:http://valor-software.com/ng2-file-upload/

    【讨论】:

    【解决方案2】:

    你可以这样做:

    //in html
    <input type="file" (click)="handleFileInput($event.target.value)">
    
    //in .ts file
    handleFileInput(file: FileList) {
        this.fileToUpload = file.item(0);
    }
    

    您可以将this.fileToUpload 附加到formdata

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-06
      • 2019-03-16
      • 2018-03-24
      • 2020-12-26
      • 2021-04-30
      • 1970-01-01
      • 2022-10-20
      • 2013-06-13
      相关资源
      最近更新 更多