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

qfe3c7zg  于 2022-11-26  发布在  iOS
关注(0)|答案(3)|浏览(121)

**我尝试使用vuews和axios上传多个图像,但在服务器端我得到了空对象。**我在标题中添加了multipart/form-data,但仍然是空对象。

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: {}

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

yk9xbfzb

yk9xbfzb1#

您忘记使用$refs。请将ref加入您的输入:

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

接下来,按如下方式访问文件:

submitFiles() {

    let formData = new FormData();

    for( var i = 0; i < this.$refs.file.files.length; i++ ){
        let file = this.$refs.file.files[i];
        formData.append('files[' + i + ']', file);
    }

    axios.post('/fileupload', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        },
      }
    ).then(function(){
    })
    .catch(function(){
    });
},

这应该是行得通的。

efzxgjgh

efzxgjgh2#

如果有人想知道,“我如何发送数据也与它”,你去那里:

formData.append('name[' + this.name + ']', name);
formData.getAll('files', 'name');
axkjgtzd

axkjgtzd3#

对于组合API,这应该有效:

const files = ref([])

function save() {
  let formData = new FormData()
  for (let file of files.value) {
    formData.append('files', file)
  }
  axios.post('/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
  .then((response) => {
  })
}

相关问题