如何在Vue.Js中使用$ http.post发送文件

And*_*end 4 javascript php vuejs2

如何使用vue.js发送文件?

以下代码对我不起作用:

<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>
Run Code Online (Sandbox Code Playgroud)

当我做console.log(this.request.file)我得到FILE [object File]

这是.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;
        }
Run Code Online (Sandbox Code Playgroud)

但是在PHP中,我无法获取文件,响应为:{} No properties

PHP代码:

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

Nik*_*ita 5

将ref属性添加到输入:

<input ref="file-input" .../>
Run Code Online (Sandbox Code Playgroud)

在控制器中,您应该编写动作:

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
  });
}    
Run Code Online (Sandbox Code Playgroud)

在php端点中,您上传的文件将位于表单请求对象中。