使用 VueJS、axios 和 Laravel 上传文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44850820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:14:28  来源:igfitidea点击:

Uploading files with VueJS, axios and Laravel

laravelvue.jssingle-page-applicationaxios

提问by Azat Akmyradov

Hello I am building one project. Where user can send up to 5 images and up to 10 songs with the text. But when I send request to the server, where I handle with Laravel, I can't get those files.

您好,我正在构建一个项目。用户可以在其中发送最多 5 张图像和最多 10 首带有文本的歌曲。但是当我向服务器发送请求时,我用 Laravel 处理,我无法获取这些文件。

// my data object from VueJS
data() {
  return {
    formData: new FormData(),
    pikir: {
      body: '',
    },
    isLoading: false,
    images: [],
    songs: [],
  }
}

// imagePreview method from VuejS
imagePreview(event) {
  let input = event.target;
  if (input.files[0]) {
    if (input.files.length <= 5) {
      
      for (let i = 0; i < input.files.length; i++) {
        let reader = new FileReader();

        reader.onload = e => {
          this.images.push(e.target.result);
        }

        reader.readAsDataURL(input.files[i]);
      }
      
      Array.from(Array(event.target.files.length).keys())
        .map(x => {
        
          this.formData
            .append('images',
              event.target.files[x], event.target.files[x].name);
          
      });
      
    } else {
      alert('You can upload up to 5 images');
    }
  }
}

// musicPreview method from VueJS
musicPreview(event) {
  let input = event.target;
  if (input.files.length <= 5) {
    for (let i = 0; i < input.files.length; i++) {
      this.songs.push(input.files[i].name.replace('.mp3', ''));
    }
     
    Array.from(Array(event.target.files.length).keys())
      .map(x => {

        this.formData
          .append('songs',
            event.target.files[x], event.target.files[x].name);

    });
    
  } else {
    alert('You can upload up to 10 songs');
  }
}

// sharePikir method from VueJS
sharePikir() {
  this.formData.append('body', this.pikir.body);
  
  axios.put('/api/pikirler', this.formData)
    .then(response => {
      this.pikir.body = '';
      this.isLoading = false;
    })
    .catch(() => {
      this.isLoading = false;
    });
},
<form action="#" id="share-pikir">
  <label for="pikir">
    N?me payla?mak isley?rsiňiz? {{ pikirSymbolLimit }}
  </label>
  
  <input type="text" name="pikir" id="pikir" maxlength="255"
    v-model="pikir.body"
    @keyup="handleSymbolLimit()">

  <div class="emoji">
      <a href="#"><i class="fa fa-smile-o"></i> </a>
  </div>

  <div class="photo-music left">
    <label for="music-upload">
      <i class="fa fa-music"></i>
    </label>
      
     <input type="file" name="songs[]" id="music-upload" 
      accept="audio/mp3"
      @change="musicPreview($event)"
      multiple>
      
      <i class="divider"></i>
     
      <label for="image-upload">
        <i class="fa fa-image"></i>
      </label>
      
     <input type="file" name="images[]" id="image-upload" 
      @change="imagePreview($event)"
      multiple>
      
  </div>

  <div class="share right">
  
    <button
      :class="{ 'btn-medium': true, 'is-loading': isLoading }"
      @click.prevent="sharePikir($event)">
      Payla?mak
    </button>
    
  </div>
  
</form>

I put my front end stuff above and in my Laravel side I just return all requests:

我把前端的东西放在上面,在我的 Laravel 端,我只返回所有请求:

public function store(){
    return request()->all();
}

And these are what I get from request:

这些是我从请求中得到的:

Image

图片

Image 2

图 2

Image 3

图 3

I couldn't found what is wrong. Thank you in advance.

我找不到问题所在。先感谢您。

回答by Dicky Eka

this my solutuion

这是我的解决方案

export default {
    data (){
        return {
            attachment : { name : null,file: null }
        }
    },
    methods : {
        onFileChange(event) {
            this.attachment.file = event.target.files[0]
        },
        attachmentCreate() {
            var form = new FormData();

            form.append('name',this.attachment.name);
            form.append('file',this.attachment.file);
            this.$http.post('attachment',form).then(response=>{
               console.log("oke")
            })
        },
    }
 }
<input type="file" class="form-control" @change="onFileChange">

回答by Sagar Chamling

Oh yeah! you're missing this part. You need to define this.

哦耶!你错过了这一部分。你需要定义这个。

axios.defaults.headers.post['Content-Type'] = 'multipart/form-data';