【问题标题】:How to send an file with $http.post in Vue.Js如何在 Vue.Js 中使用 $http.post 发送文件
【发布时间】:2018-07-08 04:51:45
【问题描述】:

如何使用 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)

【问题讨论】:

    标签: javascript php vuejs2


    【解决方案1】:

    在输入中添加 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 端点中,您上传的文件将在表单请求对象中。

    【讨论】:

    • 感谢您的回复,但是,现在我在 $request = json_decode(file_get_contents('php://input')); var_dump($request); | imgur.com/Dw0XwpU,如何在 php 中接收这个文件?
    • 尝试转储 $_FILES,official doc
    【解决方案2】:

    使用FormDataappend()函数:

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

    【讨论】:

    • 感谢您的回复,但是,现在我在 $request = json_decode(file_get_contents('php://input')); var_dump($request); | imgur.com/Dw0XwpU
    • 使用$_FILES。我看到你解决了这个问题,祝你好运。
    猜你喜欢
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 2019-03-11
    • 2017-02-06
    • 2019-10-02
    相关资源
    最近更新 更多