android上传图片至服务器

服务器端代码:

package servie;

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

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

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

/**
 * Servlet implementation class UpLoadImage
 */
public class UpLoadImage extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpLoadImage() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
       // User user=(User)session.getAttribute("user");
       // long id=user.getId();
        //String path=request.getSession().getServletContext().getRealPath("/");
        
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);
        try {
         List<FileItem> items = sfu.parseRequest(request);
         for(int i =0;i<items.size();i++){
          FileItem item =items.get(i);
          if(item.isFormField()){
           String name = item.getString();
           System.out.println("name"+name);
          }
          else{
           ServletContext context  = getServletContext();
           String path  =context.getRealPath("/pic");
           //File file = new File(path+"/pic");
           //file.mkdir();
           
           String fileName1 = item.getName();
           String fileName = fileName1.substring(fileName1.lastIndexOf("/")+1);
           File file = new File(path+"/"+fileName);
           
           item.write(file);
           System.out.println("成功!");
           
          }
         }
        } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        }
    }

}

android客户端代码

package com.example.imageupload;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

@SuppressLint("NewApi")
public class MainActivity extends Activity {

    private String newName ="image.jpg";
    private String uploadFile ="/sdcard/EditPlus.jpg";
    private String actionUrl ="http://172.16.77.58:8080/WebImageUpload/UpLoadImageTest";
    private TextView mText1;
    private TextView mText2;
    private Button mButton;
    
    @SuppressLint("NewApi")
    @Override
      public void onCreate(Bundle savedInstanceState)
      {
        super.onCreate(savedInstanceState);
        
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()  
        .detectDiskReads()  
        .detectDiskWrites()  
        .detectNetwork()   // or .detectAll() for all detectable problems  
        .penaltyLog()  
        .build());  
         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()  
        .detectLeakedSqlLiteObjects()  
        .detectLeakedClosableObjects()  
        .penaltyLog()  
        .penaltyDeath()  
        .build());  
        
        
        
        setContentView(R.layout.main);
        
        mText1 = (TextView) findViewById(R.id.myText2);
        //"文件路径:
"+
        mText1.setText(uploadFile);
        mText2 = (TextView) findViewById(R.id.myText3);
        //"上传网址:
"+
        mText2.setText(actionUrl);
        /* 设置mButton的onClick事件处理 */    
        mButton = (Button) findViewById(R.id.myButton);
        mButton.setOnClickListener(new View.OnClickListener()
        {
          public void onClick(View v)
          {
            uploadFile();
          }
        });
      }
      /* 上传文件至Server的方法 */
      private void uploadFile()
      {
        String end ="
";
        String twoHyphens ="--";
        String boundary ="*****";
        try
        {
          URL url =new URL(actionUrl);
          HttpURLConnection con=(HttpURLConnection)url.openConnection();
          /* 允许Input、Output,不使用Cache */
          con.setDoInput(true);
          con.setDoOutput(true);
          con.setUseCaches(false);
          /* 设置传送的method=POST */
          con.setRequestMethod("POST");
          /* setRequestProperty */
          con.setRequestProperty("Connection", "Keep-Alive");
          con.setRequestProperty("Charset", "UTF-8");
          con.setRequestProperty("Content-Type",
                             "multipart/form-data;boundary="+boundary);
          /* 设置DataOutputStream */
          DataOutputStream ds = new DataOutputStream(con.getOutputStream());
          ds.writeBytes(twoHyphens + boundary + end);
          ds.writeBytes("Content-Disposition: form-data; "+
                        "name="file1";filename=""+
                        newName +"""+ end);
          ds.writeBytes(end);  
          /* 取得文件的FileInputStream */
          FileInputStream fStream =new FileInputStream(uploadFile);
          /* 设置每次写入1024bytes */
          int bufferSize =1024;
          byte[] buffer =new byte[bufferSize];
          int length =-1;
          /* 从文件读取数据至缓冲区 */
          while((length = fStream.read(buffer)) !=-1)
          {
            /* 将资料写入DataOutputStream中 */
            ds.write(buffer, 0, length);
          }
          ds.writeBytes(end);
          ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
          /* close streams */
          fStream.close();
          ds.flush();
          /* 取得Response内容 */
          InputStream is = con.getInputStream();
          int ch;
          StringBuffer b =new StringBuffer();
          while( ( ch = is.read() ) !=-1 )
          {
            b.append( (char)ch );
          }
          /* 将Response显示于Dialog */
          showDialog("上传成功"+b.toString().trim());
          /* 关闭DataOutputStream */
          ds.close();
        }
        catch(Exception e)
        {
          showDialog("上传失败"+e);
        }
      }
      /* 显示Dialog的method */
      private void showDialog(String mess)
      {
        new AlertDialog.Builder(MainActivity.this).setTitle("Message")
         .setMessage(mess)
         .setNegativeButton("确定",new DialogInterface.OnClickListener()
         {
           public void onClick(DialogInterface dialog, int which)
           {          
           }
         })
         .show();
      }

}

 转自:http://www.cnblogs.com/gzggyy/archive/2011/08/02/2125237.html

原文地址:https://www.cnblogs.com/licomeback/p/3457011.html