programing

$http로 파일을 보내는 방법.Vue에 투고합니다.Js

itsource 2022. 7. 29. 23:41
반응형

$http로 파일을 보내는 방법.Vue에 투고합니다.Js

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)

입력에 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 엔드포인트에서는 업로드된 파일이 폼 요청 오브젝트입니다.

폼 데이터 사용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'
   }
})

언급URL : https://stackoverflow.com/questions/48502176/how-to-send-an-file-with-http-post-in-vue-js

반응형