带参数的Vue文件上传

时间:2019-02-27 22:39:05

标签: vue.js asp.net-core axios

伙计们,我创建了一个组件来上传文件及其到目前为止的工作,但是我还希望与数据一起传递一些参数,例如

HTML

<div class="col-md-4">
      <div class="container">
        <div class="large-12 medium-12 small-12 cell">
          <label>
            Files
            <input type="file" name="file" ref="files" multiple v-on:change="fileChange($event.target.files)" />
          </label>
          <v-btn outline color="primary" dark v-on:click="upload()">Submit</v-btn>
        </div>
      </div>
  </div>

脚本

import api from '../store/api.js'
  import axios from 'axios'

  export default {
    name: 'Profile',
    data() {
      return {
        records: [],
        application: [],
        profile: [],
        history: [],
        userValues: [],        
        files: new FormData()
     },
    fileChange() {
        for (var key in event.target.files) {
          this.files.append('files', event.target.files[key]);
        }
      },
      upload() {
          axios.post('/api/upload', this.files)
      .then(result => {
      console.dir(result.data);
    }, error => {
      console.error(error);
    });
  }

在这里(axios.post('/ api / upload',this.files))我想包括 电子邮件:this.profile.email

因为我要将此参数添加到后端的文件名中

控制器

[HttpPost, DisableRequestSizeLimit]
    public ActionResult UploadFile(string email)
    {

        var files = Request.Form.Files;
        foreach (var file in files)
        {
            string folderName = "BasteDocuments";
            string webRootPath = _hostingEnvironment.WebRootPath;
            string newPath = Path.Combine(webRootPath, folderName);
            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }
            if (file.Length > 0)
            {
                string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                string newname = email + "_" + fileName;
                string fullPath = Path.Combine(newPath, newname);
                using (var stream = new FileStream(fullPath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }
            }

        }
        return Ok();
    }

1 个答案:

答案 0 :(得分:1)

鉴于this.files是一个FormData实例,您应该可以set想要的任何字段。例如

upload () {
  this.files.set('email', this.profile.email)

  axios.post('/api/upload', this.files)...

我不太了解.NET MVC,但这会在请求中添加email作为表单参数。