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

时间:2018-01-29 13:15:49

标签: 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>

当我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;
        }

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

PHP代码:

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

2 个答案:

答案 0 :(得分:4)

将ref属性添加到输入:

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

在控制器中你应该写动作:

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
  });
}    

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

答案 1 :(得分:0)

使用FormData if let newVC = shouldAdd { navigationController?.pushViewController(newVC, animated: true) } if var stack = navigationController?.viewControllers { stack.remove(at: shoudlRemoveIndex) navigationController?.viewControllers = stack } 函数:

append()