Vue File Upload with Parameters

2019-08-17 08:47发布

Hi Guys i create a component to upload files and its working so far, but along with the data I'll like to pass some parameters too, for example

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>

Script

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);
    });
  }

here (axios.post('/api/upload', this.files)) i would like to include email: this.profile.email

Because I'm adding this parameter to the file name on my backend

Controller

[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条回答
别忘想泡老子
2楼-- · 2019-08-17 08:56

Given this.files is a FormData instance, you should be able to set any field you want. For example

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

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

I don't know .NET MVC very well any more but this would add email as a form param in the request.

查看更多
登录 后发表回答