Vuejs多个文件上传一次仅上传1个文件

时间:2019-02-25 20:44:39

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

伙计们,我正在开发VueJS应用程序,并且正在使用net core作为后端,

我有一个具有上传功能的组件,该组件正在运行但未达到预期的效果,例如,如果我选择上传3个文件,它将仅上传3个文件中的第一个。

我的HTML

<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>

我的脚本的一部分

  export default {
    name: 'Profile',
    data() {
      return {
        records: [],
        application: [],
        profile: [],
        history: [],
        userValues: [],
        dialog: false,
        notifications: false,
        sound: true,
        widgets: false,
        files: new FormData()        
      };
    },
    methods: {
      fileChange(fileList) {
        this.files.append("file", fileList[0], fileList[0].name);
      },
      upload() {
        axios({ method: "POST", "url": "/api/upload", "data": this.files }).then(result => {
          console.dir(result.data);
        }, error => {
          console.error(error);
        });
      }

还有我的控制器

 [Produces("application/json")]
[Route("api/[controller]")]
public class UploadController : Controller
{
    private IHostingEnvironment _hostingEnvironment;

    public UploadController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    [HttpPost, DisableRequestSizeLimit]
    public ActionResult UploadFile()
    {
        var email = "test@email.com";
        try
        {

            var file = Request.Form.Files[0];
            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 Json("Upload Successful.");
        }
        catch (System.Exception ex)
        {
            return Json("Upload Failed: " + ex.Message);
        }
    }
}

我还希望连同文件一起传递电子邮件:this.profile.email作为来自vue的参数。

就像我说的那样,它可以正常工作,但当时只有一个文件。

1 个答案:

答案 0 :(得分:0)

var file = Request.Form.Files[0];这将仅弹出请求中的第一个文件。相反,您需要检查

而是循环访问文件:

foreach(uploadedFile in Request.Form.Files) {

}