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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles