如上面的问题所述,我正在尝试将文件从okhttp3上传到服务器 .
我总是从codeIgniter部分接收'你没有选择要上传的文件' .
这是我的代码
Android :
public void sendItem(File item) {
Response response = null;
MediaType mediaType = MediaType.parse(FileUtils.getMimeType(item));
try {
RequestBody formBody = new MultipartBody.Builder().addFormDataPart("item", item.getName(), RequestBody.create(mediaType, item)).build();
Request request = new Request.Builder().url("index.php").post(formBody).build();
response = client.newCall(request).execute();
int statusCode = response.code(); // always 500
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null)
response.close();
}
}
Server Code:
function upload(){
$config['upload_path'] = '.../assets/...';
$this->load->library('upload', $config);
$this->upload->initialize($config);
$media = 'item';
if (!$this->upload->do_upload($media)) {
$error = array('error' => $this->upload->display_errors());
print_r($error);
}else{
$stuff = $this->upload->data();
return $stuff ;
}
}
我究竟做错了什么?谢谢!
2 回答
我很确定CodeIgniter要求您将
$config['allowed_types']
设置为库初始化的一部分 . 默认安装不允许't set '允许类型'因此您必须根据documentation在控制器或配置文件中显式设置它 .在初始化库之前,需要添加类似
$config['allowed_types'] = 'gif|jpg|png';
的内容 .也就是说,这可能不是你唯一的问题 .
你可以在服务器代码中执行
print_r($_FILES);
并查看文件数据是否在该变量中发送?只有在$ _FILES中没有发送文件时,才会从CodeIgniter的上传库中显示“您没有选择要上传的文件”的消息 .
您还应该尝试回显
print_r($_POST);
以确定您的文件数据是来自$ _POST还是来自$ _FILES .