首页 文章

在角度5的ngform提交功能上访问文件上传数据?

提问于
浏览
0

我正在使用文件输入和其他输入字段的ngform . 目前,我在提交时使用ngmodel将数据传递给组件 . 但我不知道如何使用ngmodel执行文件上传 . 在后端我使用的是Laravel .

目前我能够在组件函数 handleFileInput 中获取文件数据 . 我想将这些数据与其他表单输入字段一起传递 . 我该如何实现?

Template code

<div class="form-group">
<label for="file">Choose File</label>
<input type="file" id="file" (change)="handleFileInput($event.target.files)">                               
</div>

Component code

handleFileInput(files: FileList) {
      this.fileToUpload = files.item(0);
    }

onSubmit Method

onSubmit() {
        this.loading = true;
        this._dataService.create(this.model, company_url).subscribe(data => {
            this.submitted = true;
            this.loading = false;
            this.companyForm.reset();
        },
            error => {
                this.loading = false; console.log(error);
                this.error_message = error;
            });
    }

1 回答

  • 1

    您正在进行变更检测的部分是正确的 .

    只需要创建一个formdata并使用您的帖子请求提交该formdata . 您不必在角度方面设置内容类型,Angular会为您完成这项工作 .

    我正在为您提供我的角度节点示例希望这可以帮助您 .

    我在我的例子中使用了multer来存储文件 .

    Angular componenet

    // Create Variable for your file and formdata.
    selectedFile: File = null;
    fd = new FormData();
    
    constructor(private http: HttpClient){}
    
    // When file change is detected append your file to your formdata and on submit post the request.
    handleFileInput(event) {
          this.selectedFile = <File>event.target.files[0];
          this.fd.append('file', this.selectedFile, this.selectedFile.name);
        }
    
    onSubmit() {
        this.http.post(url, this.fd)
        .subscribe((data)=>{console.log(data);});
    }
    

    Node route file.

    var multer = require("multer");
    const storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, './upload')
        },
        filename: function (req, file, cb) {
            cb(null, file.originalname)
        }
    })
    const upload = multer({
        storage: storage
    });
    var fs = require('fs');
    
    router.post('/uploadprofile', auth, upload.single('image'), (req, res) => {
       res.send('file uploaded');
    });
    

相关问题