Home Backend Development PHP Tutorial Android图片异步上传到PHP服务器实例

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

Jun 20, 2016 pm 12:41 PM

背景

网上很多上传到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.   
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles