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

WBOY
Release: 2016-06-20 12:41:42
Original
939 people have browsed it

背景

网上很多上传到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.   
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!