Android通过http传输文件到servlet(2)

<uses-permission Android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>

添加jar包的时候可能编译不过,java.lang.NoClassDefFoundError错误,下面给出办法:

1,添加jar包

2,把jar包放在libs文件中,如图

Android通过http传输文件到servlet

下面是servlet代码:

import java.io.File ;
import java.io.IOException ;
import java.util.Iterator ;
import java.util.List ;

import javax.servlet.ServletException ;
import javax.servlet.http.HttpServlet ;
import javax.servlet.http.HttpServletRequest ;
import javax.servlet.http.HttpServletResponse ;

import org.apache.commons.fileupload.FileItem ;
import org.apache.commons.fileupload.disk.DiskFileItemFactory ;
import org.apache.commons.fileupload.servlet.ServletFileUpload ;

public class TestServlets extends HttpServlet

{
  private String uploadPath = "D:\\temp" ;    // 上传文件的目录
  private String tempPath = "d:\\temp\\buffer\\" ; // 临时文件目录
  private File tempPathFile ;

public void init( ) throws ServletException
   {
    File uploadFile = new File ( uploadPath ) ;
    if ( ! uploadFile.exists ( ) )
     {
      uploadFile.mkdirs ( ) ;
     }
    File tempPathFile = new File ( tempPath ) ;
    if ( ! tempPathFile.exists ( ) )
     {
      tempPathFile.mkdirs ( ) ;
     }
   }

public void doPost( HttpServletRequest request ,
    HttpServletResponse response ) throws ServletException ,
    IOException
   {
    try
     {
      // Create a factory for disk-based file items
      DiskFileItemFactory factory = new DiskFileItemFactory ( ) ;
      // Set factory constraints
      factory.setSizeThreshold ( 4096 ) ; // 设置缓冲区大小,这里是4kb
      factory.setRepository ( tempPathFile ) ;// 设置缓冲区目录
      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload (
        factory ) ;
      // Set overall request size constraint
      upload.setSizeMax ( 4194304 ) ; // 设置最大文件尺寸,这里是4MB
      List < FileItem > items = upload
        .parseRequest ( request ) ;// 得到所有的文件
      Iterator < FileItem > i = items.iterator ( ) ;
      while ( i.hasNext ( ) )
       {
        FileItem fi = ( FileItem ) i.next ( ) ;
        String fileName = fi.getName ( ) ;
        if ( fileName != null )
         {
          File fullFile = new File (
            fi.getName ( ) ) ;
          File savedFile = new File ( uploadPath ,
            fullFile.getName ( ) ) ;
          fi.write ( savedFile ) ;
         }
       }
      System.out.print ( "upload succeed" ) ;
     }
    catch ( Exception e )
     {
      System.out.println ( e.getMessage ( ) ) ;
      // 可以跳转出错页面
      e.printStackTrace ( ) ;
     }
   }
 }

jar包的下载地址

免费下载地址在

用户名与密码都是

具体下载目录在 /2013年资料/1月/20日/Android通过http传输文件到servlet

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/edf1e152ab63d44d694cd17024d2f6a9.html