2017-08-11 255 views
0

我試圖上傳一個圖像文件從反應原生到我的php服務器。我的問題是如何發佈文件對象到PHP。從反應本機上傳圖像文件到php服務器

我的javascript代碼:

storePicture(){ 
    const file = { 
    uri: this.state.selected[0].uri, 
    name: this.state.selected[0].filename, 
    type: 'image/jpg' 
    } 


    fetch('http://localhost:8888/s3/index.php', { 
    method: 'POST', 
    body: JSON.stringify({ 
     file: file 
    }) 
    }) 

    .then((response) => response.json()) 
    .then((responseJson) => { 
    console.log(responseJson.status) 

    }) 
} 

我的PHP代碼:

$data_back = json_decode(file_get_contents('php://input')); 

$file = $data_back->{"file"}; 
+1

預期的行爲是什麼?究竟發生了什麼? – user3080953

回答

0

你不能字符串化這樣的。嘗試創建一個FormData對象,將該文件附加到它並將FormData添加到正文。

let formData = new FormData(); 
formData.append("image", this.state.fileInputElement.files[0]); 

fetch('http://localhost:8888/s3/index.php', { 
method: 'POST', 
body: formData 
}) 
相關問題