Android图片异步上传到PHP服务器实例

WBOY
發布: 2016-06-20 12:41:42
原創
916 人瀏覽過

背景

网上很多上传到java服务器上的,找了好久,找到了上传到php的了,思路跟我当初想的差不多,就是POST过去。废话不多说,直接上图看代码。

PHP代码

PHP代码

  1. $target_path   =  "./upload/" ; //接收文件目录   
  2. $target_path  =  $target_path  .  basename (  $_FILES [ 'uploadedfile' ][ 'name' ]);  
  3. if (move_uploaded_file( $_FILES [ 'uploadedfile' ][ 'tmp_name' ],  $target_path )) {  
  4.     echo   "The file " .   basename (  $_FILES [ 'uploadedfile' ][ 'name' ]).  " has been uploaded" ;  
  5. }   else {  
  6.     echo   "There was an error uploading the file, please try again!"  .  $_FILES [ 'uploadedfile' ][ 'error' ];  
  7. }  
  8. ?>  

Android代码

上传的主要代码:

Java代码

  1. private   void  uploadFile(String uploadUrl)  
  2.   {  
  3.     String end =  "\r\n" ;  
  4.     String twoHyphens =  "--" ;  
  5.     String boundary =  "******" ;  
  6.      try   
  7.     {  
  8.       URL url =  new  URL(uploadUrl);  
  9.       HttpURLConnection httpURLConnection = (HttpURLConnection) url  
  10.           .openConnection(); //http连接   
  11.        // 设置每次传输的流大小,可以有效防止手机因为内存不足崩溃   
  12.          
  13.       httpURLConnection.setChunkedStreamingMode( 128  *  1024 ); // 128K   
  14.        // 允许输入输出流   
  15.       httpURLConnection.setDoInput( true );  
  16.       httpURLConnection.setDoOutput( true );  
  17.       httpURLConnection.setUseCaches( false );  
  18.        // 使用POST方法   
  19.       httpURLConnection.setRequestMethod( "POST" );  
  20.       httpURLConnection.setRequestProperty( "Connection" ,  "Keep-Alive" ); //保持一直连接   
  21.       httpURLConnection.setRequestProperty( "Charset" ,  "UTF-8" ); //编码   
  22.       httpURLConnection.setRequestProperty( "Content-Type" ,  
  23.            "multipart/form-data;boundary="  + boundary); //POST传递过去的编码   
  24.   
  25.       DataOutputStream dos =  new  DataOutputStream(  
  26.           httpURLConnection.getOutputStream()); //输出流   
  27.       dos.writeBytes(twoHyphens + boundary + end);  
  28.       dos.writeBytes( "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""   
  29.           + srcPath.substring(srcPath.lastIndexOf( "/" ) +  1 )  
  30.           +  "\""   
  31.           + end);  
  32.       dos.writeBytes(end);  
  33.   
  34.       FileInputStream fis =  new  FileInputStream(srcPath); //文件输入流,写入到内存中   
  35.        byte [] buffer =  new   byte [ 8192 ];  // 8k   
  36.        int  count =  0 ;  
  37.        // 读取文件   
  38.        while  ((count = fis.read(buffer)) != - 1 )  
  39.       {  
  40.         dos.write(buffer,  0 , count);  
  41.       }  
  42.       fis.close();  
  43.   
  44.       dos.writeBytes(end);  
  45.       dos.writeBytes(twoHyphens + boundary + twoHyphens + end);  
  46.       dos.flush();  
  47.   
  48.       InputStream is = httpURLConnection.getInputStream(); //http输入,即得到返回的结果   
  49.       InputStreamReader isr =  new  InputStreamReader(is,  "utf-8" );  
  50.       BufferedReader br =  new  BufferedReader(isr);  
  51.       String result = br.readLine();  
  52.   
  53.       Toast.makeText( this , result, Toast.LENGTH_LONG).show(); //将结果输出   
  54.       dos.close();  
  55.       is.close();  
  56.   
  57.     }  catch  (Exception e)  
  58.     {  
  59.       e.printStackTrace();  
  60.       setTitle(e.getMessage());  
  61.     }  
  62.   }  

因为安卓4.0之后耗时间的操作要求都在非UI线程中操作,即将前面的AsyncTask拿来用了吧~

AsyncTask传送门: http://www.cnblogs.com/yydcdut/p/3707960.html

在这个类中,将上传的操作放在doInBackground当中,可以有ProgressDialog显示上传了多少:

Java代码

  1. // Read file   
  2. bytesRead = fileInputStream.read(buffer,  0 , bufferSize);  
  3.   
  4. while  (bytesRead >  0 ) {  
  5.     outputStream.write(buffer,  0 , bufferSize);  
  6.     length += bufferSize;  
  7.     progress = ( int ) ((length *  100 ) / totalSize);  
  8.     publishProgress(progress);  
  9.   
  10.     bytesAvailable = fileInputStream.available();  
  11.     bufferSize = Math.min(bytesAvailable, maxBufferSize);  
  12.     bytesRead = fileInputStream.read(buffer,  0 , bufferSize);  
  13. }  
  14. outputStream.writeBytes(lineEnd);  
  15. outputStream.writeBytes(twoHyphens + boundary + twoHyphens  
  16.         + lineEnd);  
  17. publishProgress( 100 );  

还有就是,注意权限哟:

XML/HTML代码

  1.   
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!