使用vue js和axios上传多个文件

编程入门 行业动态 更新时间:2024-10-28 20:25:59
本文介绍了使用vue js和axios上传多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用vuejs和axios上传多张图片,但在服务器端却出现了空对象.我在标头中添加了multipart/form-data,但仍然为空对象.

I am trying to upload multiple images using vuejs and axios but on server side i am getting empty object. I added multipart/form-data in header but still empty object.

submitFiles() { /* Initialize the form data */ let formData = new FormData(); /* Iteate over any file sent over appending the files to the form data. */ for( var i = 0; i < this.files.length; i++ ){ let file = this.files[i]; console.log(file); formData.append('files[' + i + ']', file); } /*`enter code here` Make the request to the POST /file-drag-drop URL */ axios.post( '/fileupload', formData, { headers: { 'Content-Type': 'multipart/form-data' }, } ).then(function(){ }) .catch(function(){ }); },

HTML:

<form method="post" action="#" id="" enctype="multipart/form-data"> <div class="form-group files text-center" ref="fileform"> <input type="file" multiple="multiple"> <span id='val'></span> <a class="btn" @click="submitFiles()" id='button'>Upload Photo</a> <h6>DRAG & DROP FILE HERE</h6> </div>

我的服务器端代码:

class FileSettingsController extends Controller { public function upload(Request $request){ return $request->all(); } }

输出:

{files: [{}]} files: [{}] 0: {}

Console.log()结果: File(2838972) {name: "540340.jpg", lastModified: 1525262356769, lastModifiedDate: Wed May 02 2018 17:29:16 GMT+0530 (India Standard Time), webkitRelativePath: "", size: 2838972, …}

Console.log() result: File(2838972) {name: "540340.jpg", lastModified: 1525262356769, lastModifiedDate: Wed May 02 2018 17:29:16 GMT+0530 (India Standard Time), webkitRelativePath: "", size: 2838972, …}

推荐答案

您忘记了使用$refs.将ref添加到您的输入中:

You forgot to use $refs. Add ref to your input:

<input type="file" ref="file" multiple="multiple">

接下来,像这样访问您的文件:

Next, access your files like this:

submitFiles() { let formData = new FormData(); for( var i = 0; i < this.$refs.file.files.length; i++ ){ let file = this.$refs.file.files[i]; console.log(file); formData.append('files[' + i + ']', file); } axios.post( '/fileupload', formData, { headers: { 'Content-Type': 'multipart/form-data' }, } ).then(function(){ }) .catch(function(){ }); },

这应该可行.

更多推荐

使用vue js和axios上传多个文件

本文发布于:2023-10-12 03:06:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483564.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   上传   文件   vue   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!