android上傳圖片至服務器

本實例實現了android上傳手機圖片至服務器,服務器進行保存
複製代碼
  1. 服務器servlet代碼
  2. public void doPost(HttpServletRequest request, HttpServletResponse response)  
  3.            throws ServletException, IOException {  
  4.             
  5.            String temp=request.getSession().getServletContext().getRealPath("/")+"temp";   //臨時目錄
  6.            System.out.println("temp="+temp);
  7.            String loadpath=request.getSession().getServletContext().getRealPath("/")+"Image"; //上傳文件存放目錄
  8.            System.out.println("loadpath="+loadpath);
  9.            DiskFileUpload fu = new DiskFileUpload();
  10.            fu.setSizeMax(1*1024*1024);   // 設置容許用戶上傳文件大小,單位:字節
  11.            fu.setSizeThreshold(4096);   // 設置最多隻容許在內存中存儲的數據,單位:字節
  12.            fu.setRepositoryPath(temp); // 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬盤的目錄
  13.           
  14.            //開始讀取上傳信息
  15.            int index=0;
  16.            List fileItems = null;
  17.                 
  18.                         
  19.                                 try {
  20.                                         fileItems = fu.parseRequest(request);
  21.                                          System.out.println("fileItems="+fileItems);
  22.                                 } catch (Exception e) {
  23.                                         e.printStackTrace();
  24.                                 }
  25.                         
  26.                 
  27.            Iterator iter = fileItems.iterator(); // 依次處理每一個上傳的文件
  28.            while (iter.hasNext())
  29.            {
  30.                FileItem item = (FileItem)iter.next();// 忽略其餘不是文件域的全部表單信息
  31.                if (!item.isFormField())
  32.                {
  33.                    String name = item.getName();//獲取上傳文件名,包括路徑
  34.                    name=name.substring(name.lastIndexOf("\\")+1);//從全路徑中提取文件名
  35.                    long size = item.getSize();
  36.                    if((name==null||name.equals("")) && size==0)
  37.                          continue;
  38.                    int point = name.indexOf(".");
  39.                    name=(new Date()).getTime()+name.substring(point,name.length())+index;
  40.                    index++;
  41.                    File fNew= new File(loadpath, name);
  42.                    try {
  43.                                         item.write(fNew);
  44.                                 } catch (Exception e) {
  45.                                         // TODO Auto-generated catch block
  46.                                         e.printStackTrace();
  47.                                 }
  48.                   
  49.                   
  50.                }
  51.                else //取出不是文件域的全部表單信息
  52.                {
  53.                    String fieldvalue = item.getString();
  54.             //若是包含中文應寫爲:(轉爲UTF-8編碼)
  55.                    //String fieldvalue = new String(item.getString().getBytes(),"UTF-8");
  56.                }
  57.            }
  58.            String text1="11";
  59.            response.sendRedirect("result.jsp?text1=" + text1);
  60.     }  

複製代碼
android客戶端代碼
複製代碼
  1. public class PhotoUpload extends Activity {
  2.     private String newName = "image.jpg";
  3.     private String uploadFile = "/sdcard/image.JPG";
  4.     private String actionUrl = "http://192.168.0.71:8086/HelloWord/myForm";
  5.     private TextView mText1;
  6.     private TextView mText2;
  7.     private Button mButton;

  8.     @Override
  9.       public void onCreate(Bundle savedInstanceState)
  10.       {
  11.         super.onCreate(savedInstanceState);
  12.         setContentView(R.layout.photo_upload);

  13.         mText1 = (TextView) findViewById(R.id.myText2);
  14.         //"文件路徑:\n"+
  15.         mText1.setText(uploadFile);
  16.         mText2 = (TextView) findViewById(R.id.myText3);
  17.         //"上傳網址:\n"+
  18.         mText2.setText(actionUrl);
  19.             
  20.         mButton = (Button) findViewById(R.id.myButton);
  21.         mButton.setOnClickListener(new View.OnClickListener()
  22.         {
  23.           public void onClick(View v)
  24.           {
  25.             uploadFile();
  26.           }
  27.         });
  28.       }

  29.       
  30.       private void uploadFile()
  31.       {
  32.         String end = "\r\n";
  33.         String twoHyphens = "--";
  34.         String boundary = "*****";
  35.         try
  36.         {
  37.           URL url =new URL(actionUrl);
  38.           HttpURLConnection con=(HttpURLConnection)url.openConnection();
  39.           
  40.           con.setDoInput(true);
  41.           con.setDoOutput(true);
  42.           con.setUseCaches(false);
  43.           
  44.           con.setRequestMethod("POST");
  45.           
  46.           con.setRequestProperty("Connection", "Keep-Alive");
  47.           con.setRequestProperty("Charset", "UTF-8");
  48.           con.setRequestProperty("Content-Type",
  49.                              "multipart/form-data;boundary="+boundary);
  50.           
  51.           DataOutputStream ds =
  52.             new DataOutputStream(con.getOutputStream());
  53.           ds.writeBytes(twoHyphens + boundary + end);
  54.           ds.writeBytes("Content-Disposition: form-data; " +
  55.                         "name=\"file1\";filename=\"" +
  56.                         newName +"\"" + end);
  57.           ds.writeBytes(end);  

  58.           
  59.           FileInputStream fStream = new FileInputStream(uploadFile);
  60.           
  61.           int bufferSize = 1024;
  62.           byte[] buffer = new byte[bufferSize];

  63.           int length = -1;
  64.           
  65.           while((length = fStream.read(buffer)) != -1)
  66.           {
  67.             
  68.             ds.write(buffer, 0, length);
  69.           }
  70.           ds.writeBytes(end);
  71.           ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

  72.           
  73.           fStream.close();
  74.           ds.flush();

  75.           
  76.           InputStream is = con.getInputStream();
  77.           int ch;
  78.           StringBuffer b =new StringBuffer();
  79.           while( ( ch = is.read() ) != -1 )
  80.           {
  81.             b.append( (char)ch );
  82.           }
  83.           
  84.           showDialog("上傳成功"+b.toString().trim());
  85.           
  86.           ds.close();
  87.         }
  88.         catch(Exception e)
  89.         {
  90.           showDialog("上傳失敗"+e);
  91.         }
  92.       }

  93.       
  94.       private void showDialog(String mess)
  95.       {
  96.         new AlertDialog.Builder(PhotoUpload.this).setTitle("Message")
  97.          .setMessage(mess)
  98.          .setNegativeButton("肯定",new DialogInterface.OnClickListener()
  99.          {
  100.            public void onClick(DialogInterface dialog, int which)
  101.            {          
  102.            }
  103.          })
  104.          .show();
  105.       }
  106.     }
相關文章
相關標籤/搜索