Android 클라이언트는 okhttp를 사용하여 PHP 서버에 파일을 업로드합니다.
Jul 29, 2016 am 08:55 AM
gt
protected
return
this
okhttp-x.x.x.jar
okhttputils-x_x_x.jar okio-x.x.x.jar 이 세 가지 jar 패키지의 경우 Android 및 서버의 키 코드가 아래에 게시되어 있습니다. 서버측 코드:
private void uplodeImage(File mFile) { //mFile一个真实存在的图片文件 if (!mFile.exists()) { Toast.makeText(MainActivity.this, "文件不存在,请修改文件路径", Toast.LENGTH_SHORT).show(); return; } OkHttpUtils.post() .url(UPLODE_URL) .addFile("file", mFile.getName(), mFile) .build() .execute(new Callback<String>() { @Override public void onError(Call arg0, Exception arg1) { System.out.println("上传文件失败"); info.setText("REEOR:upload error!"); } @Override public void onResponse(String arg0) { //System.out.println(arg0); //上传成功返回文件在服务器上的唯一路径,将此路径保存到数据库中 info.setText(arg0); //这里会返回一个包含上传文件在服务器上的唯一路径,上传成功后将这个字符串保存到数据库中去 } @Override public String parseNetworkResponse(Response arg0) throws Exception { // TODO Auto-generated method stub return arg0.body().string(); } }) ; }
로그인 후 복사
<?php class upload{ protected $fileName; protected $maxSize; protected $allowMime; protected $allowExt; protected $uploadPath; protected $imgFlag; protected $fileInfo; protected $error; protected $ext; /** * @param string $fileName * @param string $uploadPath * @param string $imgFlag * @param number $maxSize * @param array $allowExt * @param array $allowMime */ public function __construct($fileName='myFile',$uploadPath='./uploads',$imgFlag=true,$maxSize=5242880,$allowExt=array('jpeg','jpg','png','gif'),$allowMime=array('image/jpeg','image/png','image/gif')){ $this->fileName=$fileName; $this->maxSize=$maxSize; $this->allowMime=$allowMime; $this->allowExt=$allowExt; $this->uploadPath=$uploadPath; $this->imgFlag=$imgFlag; $this->fileInfo=$_FILES[$this->fileName]; } /** * 检测上传文件是否出错 * @return boolean */ protected function checkError(){ if(!is_null($this->fileInfo)){ if($this->fileInfo['error']>0){ switch($this->fileInfo['error']){ case 1: $this->error='超过了PHP配置文件中upload_max_filesize选项的值'; break; case 2: $this->error='超过了表单中MAX_FILE_SIZE设置的值'; break; case 3: $this->error='文件部分被上传'; break; case 4: $this->error='没有选择上传文件'; break; case 6: $this->error='没有找到临时目录'; break; case 7: $this->error='文件不可写'; break; case 8: $this->error='由于PHP的扩展程序中断文件上传'; break; } return false; }else{ return true; } }else{ $this->error='文件上传出错'; return false; } } /** * 检测上传文件的大小 * @return boolean */ protected function checkSize(){ if($this->fileInfo['size']>$this->maxSize){ $this->error='上传文件过大'; return false; } return true; } /** * 检测扩展名 * @return boolean */ protected function checkExt(){ $this->ext=strtolower(pathinfo($this->fileInfo['name'],PATHINFO_EXTENSION)); if(!in_array($this->ext,$this->allowExt)){ $this->error='不允许的扩展名'; return false; } return true; } /** * 检测文件的类型 * @return boolean */ protected function checkMime(){ if(!in_array($this->fileInfo['type'],$this->allowMime)){ $this->error='不允许的文件类型'; return false; } return true; } /** * 检测是否是真实图片 * @return boolean */ protected function checkTrueImg(){ if($this->imgFlag){ if(!@getimagesize($this->fileInfo['tmp_name'])){ $this->error='不是真实图片'; return false; } return true; } } /** * 检测是否通过HTTP POST方式上传上来的 * @return boolean */ protected function checkHTTPPost(){ if(!is_uploaded_file($this->fileInfo['tmp_name'])){ $this->error='文件不是通过HTTP POST方式上传上来的'; return false; } return true; } /** *显示错误 */ protected function showError(){ return (Array( 'rType'=>-30, 'rMessage'=>$this->error ) ); } /** * 检测目录不存在则创建 */ protected function checkUploadPath(){ if(!file_exists($this->uploadPath)){ mkdir($this->uploadPath,0777,true); } } /** * 产生唯一字符串 * @return string */ protected function getUniName(){ return md5(uniqid(microtime(true),true)); } /** * 上传文件 * @return string */ public function uploadFile(){ if($this->checkError()&&$this->checkSize()&&$this->checkExt()&&$this->checkMime()&&$this->checkTrueImg()&&$this->checkHTTPPost()){ $this->checkUploadPath(); $this->uniName=$this->getUniName(); $this->destination=$this->uploadPath.'/'.$this->uniName.'.'.$this->ext; if(@move_uploaded_file($this->fileInfo['tmp_name'], $this->destination)){ return Array( 'rType' => 0, 'rMessage' => $this->destination ); }else{ $this->error='文件移动失败'; $this->showError(); } }else{ return $this->showError(); } } }
로그인 후 복사
위 내용은 관련 내용을 포함하여 PHP 서버에 파일을 업로드하기 위한 Android 클라이언트의 okhttp 사용을 소개합니다. PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.
<?php require_once 'upload.class.php'; header("Content-type:text/html;charset=utf8"); $up = new upload('filename'); echo json_encode($up->uploadFile(),JSON_UNESCAPED_UNICODE);
로그인 후 복사
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

인기 기사
R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
1 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
Repo : 팀원을 부활시키는 방법
3 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
헬로 키티 아일랜드 어드벤처 : 거대한 씨앗을 얻는 방법
3 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
스플릿 소설을이기는 데 얼마나 걸립니까?
3 몇 주 전
By DDD

인기 기사
R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
1 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
Repo : 팀원을 부활시키는 방법
3 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
헬로 키티 아일랜드 어드벤처 : 거대한 씨앗을 얻는 방법
3 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
스플릿 소설을이기는 데 얼마나 걸립니까?
3 몇 주 전
By DDD

뜨거운 기사 태그

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제
Gmail 이메일의 로그인 입구는 어디에 있나요?
7310
9


자바 튜토리얼
1623
14


Cakephp 튜토리얼
1344
46


라라벨 튜토리얼
1259
25


PHP 튜토리얼
1207
29



Java에서 return 및 finally 문의 실행 순서는 무엇입니까?

iPhone에서 App Store 오류에 연결할 수 없는 문제를 해결하는 방법
