今天学习android图片上传,简单总结,供以后参考。(大神请绕路)
首先android端:
简单布局仅仅放置一个button,添加点击事件。
button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { uploadFile(); } });接下来主要处理uploadFile()方法:
首先,网络访问不能放在主线程中进行,所以直接new Thread
代码参考:
/* 上传文件至Server的方法 */ private void uploadFile() { new Thread(){ @Override public void run() { String end = "\r\n"; 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; final StringBuffer b = new StringBuffer(); while ((ch = is.read()) != -1) { b.append((char) ch); } /* 将Response显示于Dialog */ runOnUiThread(new Runnable() { @Override public void run() { showDialog("上传成功"+b.toString()); } }); /* 关闭DataOutputStream */ ds.close(); } catch (Exception e) { Log.e("error",e.toString()); runOnUiThread(new Runnable() { @Override public void run() { showDialog("上传失败"); } }); } } }.start(); } /* 显示Dialog的method */ private void showDialog(String mess) { new AlertDialog.Builder(Main2Activity.this).setTitle("Message").setMessage(mess).setNegativeButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }).show(); }参考的地址代码注释很详细,应该没有问题。
然后就是服务器端,是本地Tomcat搭建的服务器:
新建了一个UploadServlet:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/uploadServlet")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//在D盘目录下新建文件夹tempDirectory和file
String fileName = null;
File file = null;
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// FileCleaningTracker fileCleaningTracker =
// FileCleanerCleanup.getFileCleaningTracker(getServletContext());
// factory.setFileCleaningTracker(fileCleaningTracker);
// Set factory constraints
//大于500KB,先存放在d:\\tempDirectory
factory.setSizeThreshold(1024 * 500);
File tempDirectory = new File("d:\\tempDirectory");
factory.setRepository(tempDirectory);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
//最大上传5M
upload.setSizeMax(1024 * 1024 * 5);
// Parse the request
try {
List<FileItem> items = upload.parseRequest(request);
// 2. 遍历 items:
for (FileItem item : items) {
// 若是一个一般的表单域, 打印信息
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
System.out.println(name + ": " + value);
}
else {
String fieldName = item.getFieldName();
fileName = item.getName();
String contentType = item.getContentType();
long sizeInBytes = item.getSize();
System.out.println("fieldName:" + fieldName);
System.out.println("fileName:" + fileName);
System.out.println("contentType:" + contentType);
System.out.println("sizeInBytes:" + sizeInBytes);
InputStream in = item.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
//String path = getServletContext().getRealPath(
// "/WEB-INF/image");
String path = "d:\\files\\";
file = new File(path, fileName);
System.out.println("file"+file.getName());
OutputStream out = new FileOutputStream(file);
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
in.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
response.setContentType("text/html;charset=UTF-8");
ServletOutputStream os = response.getOutputStream();
String result = "path:" + file.getAbsolutePath();
os.write(result.getBytes());
}
}
同样没有几行代码,看看就应该懂了。