文件上传与下载分为客户端与服务器端,这里客户端为Android终端,服务器为web服务器,下面分别建立客户端与服务器端。
(一)客户端
客户端界面如下:
上面的界面非常简单,左边一个按钮点击后执行上传动作,左右的图片就是要上传的图片,重点看看上传的代码:
public static String uploadFiles(List<String> files,String RequestURL)
{
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.addRequestProperty("orderId", "ABC");
conn.addRequestProperty("orderIdName", "BBC");
if(files!=null)
{
/**
* 当文件不为空,把文件包装并且上传
*/
conn.connect();
OutputStream outputSteam = conn.getOutputStream();
DataOutputStream dos = new DataOutputStream(outputSteam);
StringBuilder paramsStr = new StringBuilder();
StringBuilder paramsStr2 = new StringBuilder();//
paramsStr2.append("Content-Type: application/x-www-form-urlencoded" + LINE_END);//
Map<String, String> params = new HashMap<String, String>();
params.put("orderId", "111111222");
for (String key : params.keySet()) {
paramsStr.append(key);
paramsStr.append("=");
paramsStr.append(params.get(key));
paramsStr.append("&");
}
paramsStr.deleteCharAt(paramsStr.length() - 1);
paramsStr.append(LINE_END);
paramsStr2.append("Content-Length: " + paramsStr.length() + LINE_END);
for (String file : files) {
File uploadFile = new File(file);
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=\""+uploadFile.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(uploadFile);
byte[] bytes = new byte[4096];
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();
Log.e(TAG, "response code:"+res);
if(res==200)
{
return SUCCESS;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return FAILURE;
}
以上代码注释比较详细,值得注意的是要正确的设置Content-Type属性,由于有可能上传多个文件,所以在第二个for循环中进行处理。
以上是客户端,下面来看看服务器端。
(二)服务器端
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String orderId = request.getHeader("orderId");
Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String value = request.getHeader(name);
System.out.println("参数: " + name + " = "+ value);
}
System.out.println("参数: orderId = " + orderId);
PrintWriter out = response.getWriter();
try {
List<FileItem> items = this.upload.parseRequest(request);//request.getpa
if (items != null && !items.isEmpty()) {
for (FileItem fileItem : items) {
String filename = fileItem.getName();
String filepath = filedir + File.separator + filename;
System.out.println("文件保存路径为:" + filepath);
File file = new File(filepath);
InputStream inputSteam = fileItem.getInputStream();
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();
System.out.println("文件:" + filename + "上传成功!");
}
}
System.out.println("上传文件成功!");
out.write("上传文件成功!");
} catch (FileUploadException e) {
e.printStackTrace();
out.write("上传文件失败:" + e.getMessage());
}
}
服务器端的代码更直接,调用parseRequest解析出一个文件列表,然后对这个列表进行遍历,对每个文件对象进行写文件保存到磁盘中,完成!
最后上代码:
客户端:http://download.csdn.net/detail/www586089/8717627
服务器端:http://download.csdn.net/detail/www586089/8717673