2017-08-11 250 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 
}) 
相关问题