简体   繁体   English

如何在Vue.Js中发送带有$ http.post的文件

[英]How to send an file with $http.post in Vue.Js

How can I send a file with vue.js? 如何使用vue.js发送文件?

The following code is not working for me: 以下代码对我不起作用:

<span title="Upload" class="badge badge-info">
            <input type="file" id="file" name="file" @change="uploadData" class="archive" > <i id="iarchive" class="fa fa-upload"></i> 
</span>

When I make console.log(this.request.file) I get FILE [object File] . 当我创建console.log(this.request.file)我得到FILE [object File]

Here is the .js: 这是.js:

  uploadData: function(e) {
                var files = e.target.files[0];


                this.request.action = 'upload';
                this.request.file = files;
                console.log("FILE "+this.request.file);

                this.$http.post('data/getData.php', {
                data: this.request,    
                headers: {
                           'Content-Type': 'multipart/form-data'                   
                }
              }
               ).then(function(response) {

                    console.log("RESPONSE: "+response.body);

            }, function(response) {

                alert("error");
            });
            return false;
        }

But in PHP, I can't get the file, the response is : {} No properties . 但是在PHP中,我无法获取文件,响应是: {} No properties

PHP code: PHP代码:

$request = json_decode(file_get_contents('php://input')); 
$req = $request->data;
echo json_encode($req->file)

Add ref attribute to input: 将ref属性添加到输入:

<input ref="file-input" .../>

In controller you should write action: 在控制器中你应该写动作:

uploadFile: function () {
  // try to log $refs object for deep understanding
  let fileToUpload = this.$refs.fileInput.files[0];
  let formData = new FormData();

  formData.append('fileToUpload', fileToUpload);
  this.$http.post ( 'data/getData.php', formData ).then(function () {
    // success actions
  });
}    

In php endpoint your uploaded files will be in form request object. 在php端点中,您上传的文件将位于表单请求对象中。

Use FormData append() function: 使用FormData append()函数:

var files = e.target.files[0];

var formData = new FormData();
formData.append('file', files);

this.$http.post('/data/getData.php', formData, {
   headers: {
        'Content-Type': 'multipart/form-data'
   }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM