android 上传图片到服务器端

终于做回android功能了。这次主要介绍上传图片到服务端,服务端用socket或者servlet都可以,通常socket传的都是一些比较大的文件。我们先介绍servlet吧,服务端部分我也不算比较熟,都是借用人家的博客再作修改。我们先建立一个Dynamic Web Project。名字叫uploadImage,然后给个大致图。android 上传图片到服务器端_第1张图片

还需要两个jar包。

服务端主要代码

UploadShipServlet.java:

package com.byl.servlet;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
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 UploadShipServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String path;

	public UploadShipServlet() {
		super();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		// 创建文件项目工厂对象
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// 设置文件上传路径
		String upload = this.getServletContext().getRealPath("/");
		
		// 获取系统默认的临时文件保存路径,该路径为Tomcat根目录下的temp文件夹
		String temp = System.getProperty("java.io.tmpdir");
		// 设置缓冲区大小为 5M
		factory.setSizeThreshold(1024 * 1024 * 5);
		// 设置临时文件夹为temp
		factory.setRepository(new File(temp));
		// 用工厂实例化上传组件,ServletFileUpload 用来解析文件上传请求
		ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

		// 解析结果放在List中
		try {
			List list = servletFileUpload.parseRequest(request);

			for (FileItem item : list) {
				String name = item.getFieldName();
				InputStream is = item.getInputStream();

				if (name.contains("content")) {
					System.out.println(inputStream2String(is));
				} else if (name.contains("img")) {
					try {
						path = upload+"\\"+item.getName();
						inputStream2File(is, path);
						break;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			out.write(path);  //这里我把服务端成功后,返回给客户端的是上传成功后路径
		} catch (org.apache.commons.fileupload.FileUploadException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		out.flush();
		out.close();
	}

	// 流转化成字符串
	public static String inputStream2String(InputStream is) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int i = -1;
		while ((i = is.read()) != -1) {
			baos.write(i);
		}
		return baos.toString();
	}

	// 流转化成文件
	public static void inputStream2File(InputStream is, String savePath) throws Exception {
		System.out.println("文件保存路径为:" + savePath);
		File file = new File(savePath);
		InputStream inputSteam = is;
		BufferedInputStream fis = new BufferedInputStream(inputSteam);
		FileOutputStream fos = new FileOutputStream(file);
		int f;
		while ((f = fis.read()) != -1) {
			fos.write(f);
		}
		fos.flush();
		fos.close();
		fis.close();
		inputSteam.close();

	}
}
web.xml:



  
    This is the description of my J2EE component
    This is the display name of my J2EE component
    UploadShipServlet
    com.byl.servlet.UploadShipServlet
  
  
    UploadShipServlet
    /UploadShipServlet
  

index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



  
    
    
    My JSP 'index.jsp' starting page
	
	
	    
	
	
	
  
  
  
    This is my JSP page. 
android客户端代码:

主要代码,这里用到别人封装好的工具类,方便调用。

public class UploadUtil {
    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10*1000;   //超时时间
    private static final String CHARSET = "utf-8"; //设置编码
    /**
     * android上传文件到服务器
     * @param file  需要上传的文件
     * @param RequestURL  请求的rul
     * @return  返回响应的内容
     */
    public static String uploadFile(File file, String RequestURL){
        String result = null;
        String  BOUNDARY =  UUID.randomUUID().toString();  //边界标识   随机生成
        String PREFIX = "--" , LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data";   //内容类型

        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true);  //允许输入流
            conn.setDoOutput(true); //允许输出流
            conn.setUseCaches(false);  //不允许使用缓存
            conn.setRequestMethod("POST");  //请求方式
            conn.setRequestProperty("Charset", CHARSET);  //设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            conn.connect();

            if(file!=null){
                /**
                 * 当文件不为空,把文件包装并且上传
                 */
                DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 这里重点注意:
                 * name里面的值为服务器端需要key   只有这个key 才可以得到对应的文件
                 * filename是文件的名字,包含后缀名的   比如:abc.png
                 */

                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END);
                sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while((len=is.read(bytes))!=-1){
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码  200=成功
                 * 当响应成功,获取响应的流
                 */
                int res = conn.getResponseCode();
                if(res==200){
                    InputStream input =  conn.getInputStream();
                    StringBuffer sb1= new StringBuffer();
                    int ss ;
                    while((ss=input.read())!=-1){
                        sb1.append((char)ss);
                    }
                    result = sb1.toString();
                    System.out.println(result);
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}

然后在上传的事件里面调用就可以了。

android 上传图片到服务器端_第2张图片


Data.getA()是图片的URL的路径,这样就完成了上传。是不是方便?

下面介绍socket的上传方法,服务端也是参考别人的。先建立一个java Project。

大致图是这样的:

android 上传图片到服务器端_第3张图片

socket服务端代码:

FileServer.java:

public class FileServer {  
    
    private ExecutorService executorService;//线程池  
    private int port;//监听端口  
    private boolean quit = false;//退出  
    private ServerSocket server;  
    private Map datas = new HashMap();//存放断点数据  
      
    public FileServer(int port){  
        this.port = port;  
        //创建线程池,池中具有(cpu个数*50)条线程  
        executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 50);  
    }  
    /** 
     * 退出 
     */  
    public void quit(){  
       this.quit = true;  
       try {  
           server.close();  
       } catch (IOException e) {  
       }  
    }  
    /** 
     * 启动服务 
     * @throws Exception 
     */  
    public void start() throws Exception{  
        server = new ServerSocket(port);  
        while(!quit){  
            try {  
              Socket socket = server.accept();  
              //为支持多用户并发访问,采用线程池管理每一个用户的连接请求  
              executorService.execute(new SocketTask(socket));  
            } catch (Exception e) {  
              //  e.printStackTrace();  
            }  
        }  
    }  
      
    private final class SocketTask implements Runnable{  
       private Socket socket = null;  
       public SocketTask(Socket socket) {  
           this.socket = socket;  
       }  
         
       public void run() {  
           try {  
               System.out.println("accepted connection "+ socket.getInetAddress()+ ":"+ socket.getPort());  
               PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());  
               //得到客户端发来的第一行协议数据:Content-Length=143253434;filename=xxx.3gp;sourceid=  
               //如果用户初次上传文件,sourceid的值为空。  
               String head = StreamTool.readLine(inStream);  
               System.out.println(head);  
               if(head!=null){  
                   //下面从协议数据中提取各项参数值  
                   String[] items = head.split(";");  
                   String filelength = items[0].substring(items[0].indexOf("=")+1);  
                   String filename = items[1].substring(items[1].indexOf("=")+1);  
                   String sourceid = items[2].substring(items[2].indexOf("=")+1);        
                   long id = System.currentTimeMillis();//生产资源id,如果需要唯一性,可以采用UUID  
                   FileLog log = null;  
                   if(sourceid!=null && !"".equals(sourceid)){  
                       id = Long.valueOf(sourceid);  
                       log = find(id);//查找上传的文件是否存在上传记录  
                   }  
                   File file = null;  
                   int position = 0;  
                   if(log==null){//如果不存在上传记录,为文件添加跟踪记录  
                       String path = new SimpleDateFormat("yyyy/MM/dd/HH/mm").format(new Date());  
                       File dir = new File("file/"+ path);  
                       if(!dir.exists()) dir.mkdirs();  
                       file = new File(dir, filename);  
                       if(file.exists()){//如果上传的文件发生重名,然后进行改名  
                           filename = filename.substring(0, filename.indexOf(".")-1)+ dir.listFiles().length+ filename.substring(filename.indexOf("."));  
                           file = new File(dir, filename);  
                       }  
                       save(id, file);  
                   }else{// 如果存在上传记录,读取已经上传的数据长度  
                       file = new File(log.getPath());//从上传记录中得到文件的路径  
                       if(file.exists()){  
                           File logFile = new File(file.getParentFile(), file.getName()+".log");  
                           if(logFile.exists()){  
                               Properties properties = new Properties();  
                               properties.load(new FileInputStream(logFile));  
                               position = Integer.valueOf(properties.getProperty("length"));//读取已经上传的数据长度  
                           }  
                       }  
                   }  
                     
                   OutputStream outStream = socket.getOutputStream();  
                   String response = "sourceid="+ id+ ";position="+ position+ "\r\n";  
                   //服务器收到客户端的请求信息后,给客户端返回响应信息:sourceid=1274773833264;position=0  
                   //sourceid由服务器端生成,唯一标识上传的文件,position指示客户端从文件的什么位置开始上传  
                   outStream.write(response.getBytes());  
                     
                   RandomAccessFile fileOutStream = new RandomAccessFile(file, "rwd");  
                   if(position==0) fileOutStream.setLength(Integer.valueOf(filelength));//设置文件长度  
                   fileOutStream.seek(position);//指定从文件的特定位置开始写入数据  
                   byte[] buffer = new byte[1024];  
                   int len = -1;  
                   int length = position;  
                   while( (len=inStream.read(buffer)) != -1){//从输入流中读取数据写入到文件中  
                       fileOutStream.write(buffer, 0, len);  
                       length += len;  
                       Properties properties = new Properties();  
                       properties.put("length", String.valueOf(length));  
                       FileOutputStream logFile = new FileOutputStream(new File(file.getParentFile(), file.getName()+".log"));  
                       properties.store(logFile, null);//实时记录已经接收的文件长度  
                       logFile.close();  
                   }  
                   if(length==fileOutStream.length()) delete(id);  
                   fileOutStream.close();                    
                   inStream.close();  
                   outStream.close();  
                   file = null;  
                     
               }  
           } catch (Exception e) {  
               e.printStackTrace();  
           }finally{  
               try {  
                   if(socket!=null && !socket.isClosed()) socket.close();  
               } catch (IOException e) {}  
           }  
       }  
    }  
      
    public FileLog find(Long sourceid){  
        return datas.get(sourceid);  
    }  
    //保存上传记录  
    public void save(Long id, File saveFile){  
        //日后可以改成通过数据库存放  
        datas.put(id, new FileLog(id, saveFile.getAbsolutePath()));  
    }  
    //当文件上传完毕,删除记录  
    public void delete(long sourceid){  
        if(datas.containsKey(sourceid)) datas.remove(sourceid);  
    }  
      
    private class FileLog{  
       private Long id;  
       private String path;  
       public Long getId() {  
           return id;  
       }  
       public void setId(Long id) {  
           this.id = id;  
       }  
       public String getPath() {  
           return path;  
       }  
       public void setPath(String path) {  
           this.path = path;  
       }  
       public FileLog(Long id, String path) {  
           this.id = id;  
           this.path = path;  
       }     
    }  
 
}  
然后是窗口代码ServerWindow.java:

public class ServerWindow extends Frame {
	private FileServer s = new FileServer(12345);
	private Label label;

	public ServerWindow(String title) {
		super(title);
		label = new Label();
		add(label, BorderLayout.PAGE_START);
		label.setText("服务器已经启动");
		this.addWindowListener(new WindowListener() {
			public void windowOpened(WindowEvent e) {
				new Thread(new Runnable() {
					public void run() {
						try {
							s.start();
						} catch (Exception e) {
							// e.printStackTrace();
						}
					}
				}).start();
			}

			public void windowIconified(WindowEvent e) {
			}

			public void windowDeiconified(WindowEvent e) {
			}

			public void windowDeactivated(WindowEvent e) {
			}

			public void windowClosing(WindowEvent e) {
				s.quit();
				System.exit(0);
			}

			public void windowClosed(WindowEvent e) {
			}

			public void windowActivated(WindowEvent e) {
			}
		});
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) throws IOException {
		InetAddress address = InetAddress.getLocalHost();
		ServerWindow window = new ServerWindow("文件上传服务端:" + address.getHostAddress());
		window.setSize(400, 300);
		window.setVisible(true);

	}

}
最后是流解析的代码,StreamTool.java:
public class StreamTool {

	public static void save(File file, byte[] data) throws Exception {
		FileOutputStream outStream = new FileOutputStream(file);
		outStream.write(data);
		outStream.close();
	}

	public static String readLine(PushbackInputStream in) throws IOException {
		char buf[] = new char[128];
		int room = buf.length;
		int offset = 0;
		int c;
		loop:       while (true) {
			switch (c = in.read()) {
				case -1:
				case '\n':
					break loop;
				case '\r':
					int c2 = in.read();
					if ((c2 != '\n') && (c2 != -1)) in.unread(c2);
					break loop;
				default:
					if (--room < 0) {
						char[] lineBuffer = buf;
						buf = new char[offset + 128];
						room = buf.length - offset - 1;
						System.arraycopy(lineBuffer, 0, buf, 0, offset);

					}
					buf[offset++] = (char) c;
					break;
			}
		}
		if ((c == -1) && (offset == 0)) return null;
		return String.copyValueOf(buf, 0, offset);
	}

	/**
	 * 读取流
	 * @param inStream
	 * @return 字节数组
	 * @throws Exception
	 */
	public static byte[] readStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		while( (len=inStream.read(buffer)) != -1){
			outSteam.write(buffer, 0, len);
		}
		outSteam.close();
		inStream.close();
		return outSteam.toByteArray();
	}
} 

服务端的代码差不多就这样啦。然后是客户端的代码:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText edit_fname;
    private Button btn_upload;
    private Button btn_stop;
    private ProgressBar pgbar;
    private TextView txt_result;

    private UploadHelper upHelper;
    private boolean flag = true;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            pgbar.setProgress(msg.getData().getInt("length"));
            float num = (float) pgbar.getProgress() / (float) pgbar.getMax();
            int result = (int) (num * 100);
            txt_result.setText(result + "%");
            if (pgbar.getProgress() == pgbar.getMax()) {
                Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindViews();
        upHelper = new UploadHelper(this);
    }

    private void bindViews() {
        edit_fname = (EditText) findViewById(R.id.edit_fname);
        btn_upload = (Button) findViewById(R.id.btn_upload);
        btn_stop = (Button) findViewById(R.id.btn_stop);
        pgbar = (ProgressBar) findViewById(R.id.pgbar);
        txt_result = (TextView) findViewById(R.id.txt_result);

        btn_upload.setOnClickListener(this);
        btn_stop.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_upload:
                String filename = edit_fname.getText().toString();
                flag = true;
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    File file = new File(Environment.getExternalStorageDirectory(), filename);
                    if (file.exists()) {
                        pgbar.setMax((int) file.length());
                        uploadFile(file);
                    } else {
                        Toast.makeText(MainActivity.this, "文件并不存在~", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(MainActivity.this, "SD卡不存在或者不可用", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_stop:
                flag = false;
                break;
        }
    }

    private void uploadFile(final File file) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    String sourceid = upHelper.getBindId(file);
                    Socket socket = new Socket("172.16.2.54", 12345);
                    OutputStream outStream = socket.getOutputStream();
                    String head = "Content-Length=" + file.length() + ";filename=" + file.getName()
                            + ";sourceid=" + (sourceid != null ? sourceid : "") + "\r\n";
                    outStream.write(head.getBytes());

                    PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());
                    String response = StreamTool.readLine(inStream);
                    String[] items = response.split(";");
                    String responseSourceid = items[0].substring(items[0].indexOf("=") + 1);
                    String position = items[1].substring(items[1].indexOf("=") + 1);
                    if (sourceid == null) {//如果是第一次上传文件,在数据库中不存在该文件所绑定的资源id
                        upHelper.save(responseSourceid, file);
                    }
                    RandomAccessFile fileOutStream = new RandomAccessFile(file, "r");
                    fileOutStream.seek(Integer.valueOf(position));
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    int length = Integer.valueOf(position);
                    while (flag && (len = fileOutStream.read(buffer)) != -1) {
                        outStream.write(buffer, 0, len);
                        length += len;//累加已经上传的数据长度
                        Message msg = new Message();
                        msg.getData().putInt("length", length);
                        handler.sendMessage(msg);
                    }
                    if (length == file.length()) upHelper.delete(file);
                    fileOutStream.close();
                    outStream.close();
                    inStream.close();
                    socket.close();
                } catch (Exception e) {
                    Toast.makeText(MainActivity.this, "上传异常~", Toast.LENGTH_SHORT).show();
                }
            }
        }).start();
    }

}
因为断点续传,我们需要保存上传的进度,我们需要用到数据库,这里我们定义一个数据库 管理类:

DBOpenHelper.java:

public class DBOpenHelper extends SQLiteOpenHelper {

    public DBOpenHelper(Context context) {
        super(context, "jay.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS uploadlog (_id integer primary key autoincrement, path varchar(20), sourceid varchar(20))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}
然后是数据库操作类:UploadHelper.java:

public class UploadHelper {
    private DBOpenHelper dbOpenHelper;

    public UploadHelper(Context context) {
        dbOpenHelper = new DBOpenHelper(context);
    }

    public String getBindId(File file) {
        SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select sourceid from uploadlog where path=?", new String[]{file.getAbsolutePath()});
        if (cursor.moveToFirst()) {
            return cursor.getString(0);
        }
        return null;
    }

    public void save(String sourceid, File file) {
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        db.execSQL("insert into uploadlog(path,sourceid) values(?,?)",
                new Object[]{file.getAbsolutePath(), sourceid});
    }

    public void delete(File file) {
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        db.execSQL("delete from uploadlog where path=?", new Object[]{file.getAbsolutePath()});
    }
}
还要加上之前的流解析的类:

public class StreamTool {

	public static void save(File file, byte[] data) throws Exception {
		FileOutputStream outStream = new FileOutputStream(file);
		outStream.write(data);
		outStream.close();
	}

	public static String readLine(PushbackInputStream in) throws IOException {
		char buf[] = new char[128];
		int room = buf.length;
		int offset = 0;
		int c;
		loop:       while (true) {
			switch (c = in.read()) {
				case -1:
				case '\n':
					break loop;
				case '\r':
					int c2 = in.read();
					if ((c2 != '\n') && (c2 != -1)) in.unread(c2);
					break loop;
				default:
					if (--room < 0) {
						char[] lineBuffer = buf;
						buf = new char[offset + 128];
						room = buf.length - offset - 1;
						System.arraycopy(lineBuffer, 0, buf, 0, offset);

					}
					buf[offset++] = (char) c;
					break;
			}
		}
		if ((c == -1) && (offset == 0)) return null;
		return String.copyValueOf(buf, 0, offset);
	}

	/**
	 * 读取流
	 * @param inStream
	 * @return 字节数组
	 * @throws Exception
	 */
	public static byte[] readStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		while( (len=inStream.read(buffer)) != -1){
			outSteam.write(buffer, 0, len);
		}
		outSteam.close();
		inStream.close();
		return outSteam.toByteArray();
	}
} 

这样就好了。最后给上两个服务端的源码。客户端主要代码已经给出,这里不方便给出源码。

写得不好请多多见谅

socket服务器

servlet服务器



你可能感兴趣的:(android)