android上传图片到服务器

android2.3以后都要用AsyncTask了,所以自己写了个帮助类。可以上传图片的

package com.http.util;

import java.io.File;
import java.nio.charset.Charset;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.os.AsyncTask;

/**
	 * 2.3之后的安卓版本 获取网址内容  
	 * 利用了新增加的辅助类AsyncTask
	 */
	//构造函数AsyncTask<Params, Progress, Result>参数说明:  
	//Params   启动任务执行的输入参数 
	//Progress 后台任务执行的进度 
	//Result   后台计算结果的类型 
	public class UploadImgAndInforAsyncTask extends AsyncTask<String, Integer, String>{ 

		private File myfile;
		private String requestURL;
		private String info;
		
		//为AsyncTask创建传递参数
		public UploadImgAndInforAsyncTask(String info,File file,String requestURL) {
			this.myfile = file;
			this.requestURL = requestURL;
			this.info = info;
		}
		

		//为AsyncTask自定义监听器  用来再确认图片上传成功后返回方法到Activity
		public static interface UploadListener { //定义接口函数
	        void backtoActivity(Object data); 
//	        void aaa();//公共函数用于设置监听
	    } 
	    public UploadListener uploadListener; 
		public void setUploadListener(UploadListener uploadListener) {
			this.uploadListener = uploadListener;
		}

		
		//onPreExecute()方法用于在执行异步任务前,主线程做一些准备工作    
	    @Override 
	    protected void onPreExecute() { 
	    } 
	     
	    //doInBackground()方法用于在执行异步任务,不可以更改主线程中UI  
	    @Override 
	    protected String doInBackground(String... params) {
	    	try
	        {
		    	HttpPost httpPost = ConnNet.getHttPost(requestURL);//到辅助类转换httpPos
		        MultipartEntity mpEntity = new MultipartEntity();
		        mpEntity.addPart("picture", new FileBody(myfile, "image/*", "UTF-8"));//图片
		        mpEntity.addPart("info", new StringBody(info,Charset.forName("UTF-8")));//字符串
		        httpPost.setEntity(mpEntity);
		        HttpClient client = new DefaultHttpClient();
				HttpResponse httpResponse = client.execute(httpPost);//发送
//				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) 
				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					String result = EntityUtils.toString(httpResponse.getEntity(), "utf-8"); //接收
					System.out.println("结果为:"+result);
					return result.toString();
				} 
	        }
	        catch(Exception e)
	        {
	        	System.out.println("出bug了。。。");
	        }
	        System.out.println("上传失败,请检查网络连接");
	        return null;
	    }
	    
	    //onPostExecute()方法用于异步任务执行完成后,在主线程中执行的操作 
	    @Override 
	    protected void onPostExecute(String result) { 
	        super.onPostExecute(result);     
//	        Toast.makeText(getApplicationContext(), "调用onPostExecute()方法--->异步任务执行完毕", 0).show(); 
	        //textView显示网络请求结果 
	        if(result != null)
	        {
    			System.out.println("上传成功!返回结果是:"+ result);
    			uploadListener.backtoActivity(result); 
//	    		dataDownloadListener.aaa();
	        }
	        else {
	        	System.out.println("上传失败,没有从服务器获得相应连接");
	        	uploadListener.backtoActivity(null); 
	        }
	    } 
		
	    //onProgressUpdate()方法用于更新异步执行中,在主线程中处理异步任务的执行信息    
	    @Override 
	    protected void onProgressUpdate(Integer... values) { 
	        super.onProgressUpdate(values); 
	    } 
	     
	    //onCancelled()方法用于异步任务被取消时,在主线程中执行相关的操作  
	    @Override 
	    protected void onCancelled() { 
	        super.onCancelled(); 
	        System.out.println("调用onCancelled()方法--->异步任务被取消"); 
	    }
帮助类Connet得到网址:

package com.http.util;

import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;

/**
 * 获取网络连接  connection 
 */
public class ConnNet 
{
	//将路径定义为一个常量,修改的时候也好更改
	public static String request_Send_PictureAndMessage_URL = "http://192.168.112.117:8080/HyhealthServer/uploadServer";//图片上传服务器路径
	public static String request_Get_Message_URL = "http://192.168.112.117:8080/HyhealthServer/downloadServer";//获取结果界面
	
	//通过url获取网络连接  connection 
	public static HttpURLConnection getConn(String requestURL)
	{
        String boundary ="*****";
        try
        {
			URL url =new URL(requestURL);
	        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);
	        return con;
        }catch(Exception e){
        }
		return null;
	}
	
	public static HttpPost getHttPost(String url){		
		HttpPost httpPost = new HttpPost(url);	
		System.out.println("ConnNet的url:"+url);
		return httpPost;
	}
	
	public static HttpGet getHttpGet (String url){
		HttpGet httpGet = new HttpGet(url);
		return httpGet;
	}

}
在activity中调用的时候这样:

UploadImgAndInforAsyncTask uploadImgAndInforAsyncTask = new UploadImgAndInforAsyncTask(info,myfFile,ConnNet.request_Send_PictureAndMessage_URL); 
			uploadImgAndInforAsyncTask.setUploadListener(new UploadListener()
			{ 
				@SuppressWarnings("unchecked") 
			    @Override 
			    public void backtoActivity(Object data) {
<span style="white-space:pre">				</span>这里就是通过<span style="font-family: Arial, Helvetica, sans-serif;">AsyncTask类返回的监听的值了</span>
			    } 
			}); 
			uploadImgAndInforAsyncTask.execute(ConnNet.request_Send_PictureAndMessage_URL); 
服务器上这样获得图片并保存

package com.wy.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
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.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wy.helper.JsonHelper;
import com.wy.model.AndroidHyhealth;
import com.wy.model.Hyhealth;
import com.wy.service.Myservice;

@Component
public class UploadServer extends HttpServlet {

	@Autowired
	private Myservice myservice;
	
	private String paramValue;
	private String filePath;
	private String fileName;
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");  
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
		FileItemFactory factory = new DiskFileItemFactory();    
        ServletFileUpload upload = new ServletFileUpload(factory);    
        try {     
            List items = upload.parseRequest(request);    
            Iterator iter = items.iterator();    
            while (iter.hasNext()) {    
                FileItem item = (FileItem) iter.next();    
                if (item.isFormField()) {    
                    //普通文本信息处理    
                    String paramName = item.getFieldName();    
                    paramValue = item.getString();    
                    System.out.println(paramName + ":" + paramValue);
                } else {    
                    //上传文件信息处理    
                    String loadpath=request.getSession().getServletContext().getRealPath("/")+"upload"; //上传文件存放目录
                    fileName = item.getName();
                    byte[] data = item.get();    
	                System.out.println("name="+fileName);
	                
	                int point = fileName.indexOf(".");//重命名
	                fileName=(new Date()).getTime()+fileName.substring(point,fileName.length());
	                filePath = loadpath+"/"+fileName;//文件存放位置+文件名
                    
                    FileOutputStream fos = new FileOutputStream(filePath);//写入文件
                    fos.write(data);    
                    fos.close();    
                }    
            }  
   
            
        } catch (FileUploadException e) {  
            PrintWriter out = response.getWriter();
            out.println("false");
    	    out.flush();
    	    out.close();
    	    e.printStackTrace();    
        }    
	    //给Android返回信息
        PrintWriter out = response.getWriter();
        out.println("true");
	    out.flush();
	    out.close();
	}

	public void init() throws ServletException {
		// Put your code here
	}

	public UploadServer() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
整个流程就是这样完成了




【Hyper Upload Server 超级上传服务器】 这是一款超级文件上传服务器,基异步I/O架构,采用C++语言编码实现。它支持Chromium 内核浏览器4GB以上超大文件上传和断点续传,支持IE 11以上版本的浏览 器中2GB的文件上传和断点续传,支持Windows和Linux服务器平台,支持任意格式的文件上传,尤其适合大的视频网站应用。单台服务器支持1000并发上传进程,支持PC端和智能手机端主流的浏览器。 【主要特性】 1.服务器端采用异步I/O架构设计,具有高性能I/O处理能力,尤其适用于超大文件上传; 2.服务器端采用高效内存分配技术确保在运行过程中服务器的内存开销最小化; 3.完全采用标准协议实现,因此兼容几乎所有的PC端和移动端浏览器; 4.服务器端采用C++语言自主实现,对上传文件的尺寸无限制,天生支持超大文件上传。 而基于PHP、JAVA等技术实现的文件上传服务天生无法支持超大文件上传,无法逾越2GB的最大文件尺寸瓶颈; 5.服务器端采用无缓冲即时写入方式,上传数据写入一步到位。不同于PHP、JAVA等技术实现方式需要两步写入; 6.服务器端可跨平台编译运行,支持Windows和Linux平台; 7.高性能,单台服务器支持1000个并发上传进程; 8.支持Chromium内核浏览器中4GB以上超大文件上传,文件大小不受限制; 9,。支持IE 11版本及以上的浏览器最大2GB的文件上传,客户端支持采用HTTP标准 协议上传; 10.支持断点续传,断网、关机重启均不受影响; 11.支持HTML5浏览器上传进度实时显示; 12.支持IE8及以上浏览器上传进度显示; 13.支持查看客户端在线连接, 查看方法: http://ip:port/lists 14.多浏览器兼容,包括Chrome,Firefox,Safari,IE,Opera,Edge;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值