Android上传文件,客户端+服务器源码

Android客户端使用了AFinal框架,处理图片上传的代码如下:

package cn.yubo.testupload;

import java.io.File;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
	private FinalHttp finalHttp;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        finalHttp = new FinalHttp();
        finalHttp.configTimeout(10 * 1000);
    }
    
    private void showToast(String msg){
    	Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    //上传文件
    public void upload(View view){
    	try {
    		//待上传的两个文件
			File file = new File("mnt/sdcard/Download/text.txt");
			File file2 = new File("mnt/sdcard/Download/4aa60.gif");
			//post请求需要携带的参数
			AjaxParams params = new AjaxParams();
			//将文件放入参数中
			params.put("file", file);
			params.put("file2", file2);
			//请求的URL
			String url = "http://10.8.10.138:8080/UploadFiles/UploadFileServlet";
			//post请求,三个参数分别是请求地址、请求参数、请求的回调接口
			finalHttp.post(url, params, new AjaxCallBack<String>() {

				@Override
				public void onFailure(Throwable t, int errorNo, String strMsg) {
					super.onFailure(t, errorNo, strMsg);
					showToast("上传失败, msg=" + strMsg);
				}
				
				@Override
				public void onStart() {
					super.onStart();
					showToast("开始上传");
				}

				@Override
				public void onSuccess(String t) {
					super.onSuccess(t);
					//根据服务器返回的json数据,判断上传是否成功
					if(!TextUtils.isEmpty(t)){
						try {
							JSONObject obj = new JSONObject(t);
							if(obj.optInt("result") == 1){
								showToast("上传成功");
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					
				}
				
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}
上传的主要代码在upload方法中,下面是服务器端代码,接收文件用到了commons-fileupload-1.2.2.jar和commons-io-2.3.jar两个包,接收的代码如下:

package cn.yubo.servlets;

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;
import org.json.JSONObject;

public class UploadFileServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		String path = "C:\\";//上传文件的保存路径
		factory.setRepository(new File(path));
		factory.setSizeThreshold(1024 * 1024);
		ServletFileUpload upload = new ServletFileUpload(factory);
		JSONObject jobj = new JSONObject();
		try {
			List<FileItem> list = (List<FileItem>)upload.parseRequest(request);
			for(FileItem item : list){
				String name = item.getName();
				String fileName = name.substring(name.lastIndexOf("\\") + 1);
				InputStream is = item.getInputStream();
				File f = new File(path + fileName);
				FileOutputStream fos = new FileOutputStream(f);
				int hasRead = 0;
				byte[] buf = new byte[1024];
				while((hasRead = is.read(buf)) > 0){
					fos.write(buf, 0, hasRead);
				}
				fos.close();
				is.close();
			}
			jobj.put("result", 1);
			out.print(jobj.toString());
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		out.flush();
		out.close();
	}

}
源码下载点击这里


你可能感兴趣的:(源码,android,上传,多文件上传)