标签:
一个简单的文件上传例子
1、客户端代码
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 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);
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);
Log.i("上传数据", sb.toString());
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();
Log.i("结束数据", end_data.toString());
dos.write(end_data);
dos.flush();
/**
* 获取响应码 200=成功 当响应成功,获取响应的流
*/
int res = conn.getResponseCode();
Log.e(TAG, "response code:" + res);
if (res == 200) {
result = conn.getResponseMessage();
Log.e(TAG, "result : " + result);
} else {
Log.e(TAG, "request error");
result = "NO";
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
2、服务端代码
public class UploadServlet extends HttpServlet {
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// String BOUNDARY = UUID.randomUUID().toString();
try {
request.setCharacterEncoding("UTF-8"); // 设置处理请求参数的编码格式
response.setContentType("text/html;charset=UTF-8"); // 设置Content-Type字段值
PrintWriter out = response.getWriter();
out.println("文件开始!");
// 下面的代码开始使用Commons-UploadFile组件处理上传的文件数据
FileItemFactory factory = new DiskFileItemFactory(); // 建立FileItemFactory对象
ServletFileUpload upload = new ServletFileUpload(factory);
// 分析请求,并得到上传文件的FileItem对象
List<FileItem> items = upload.parseRequest(request);
// 从web.xml文件中的参数中得到上传文件的路径
String uploadPath = "d:\\upload\\";
File file = new File(uploadPath);
if (!file.exists()) {
file.mkdir();
}
String filename = ""; // 上传文件保存到服务器的文件名
InputStream is = null; // 当前上传文件的InputStream对象
// 循环处理上传文件
for (FileItem item : items) {
// 处理普通的表单域
if (item.isFormField()) {
if (item.getFieldName().equals("filename")) {
System.out.println("文件名称 " + item.getFieldName());
// 如果新文件不为空,将其保存在filename中
if (!item.getString().equals(""))
filename = item.getString("UTF-8");
}
}
// 处理上传文件
else if (item.getName() != null && !item.getName().equals("")) {
// 从客户端发送过来的上传文件路径中截取文件名
filename = item.getName().substring(
item.getName().lastIndexOf("\\") + 1);
System.out.println("文件名称22 " + filename);
is = item.getInputStream(); // 得到上传文件的InputStream对象
}
}
// 将路径和上传文件名组合成完整的服务端路径
filename = uploadPath + "/" + filename;
// 如果服务器已经存在和上传文件同名的文件,则输出提示信息
if (new File(filename).exists()) {
new File(filename).delete();
}
// 开始上传文件
if (!filename.equals("")) {
// 用FileOutputStream打开服务端的上传文件
FileOutputStream fos = new FileOutputStream(filename);
byte[] buffer = new byte[8192]; // 每次读8K字节
int count = 0;
// 开始读取上传文件的字节,并将其输出到服务端的上传文件输出流中
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count); // 向服务端文件写入字节流
}
fos.close(); // 关闭FileOutputStream对象
is.close(); // InputStream对象
out.println("文件上传成功!");
}
} catch (Exception e) {
}
}
}
3、上传示例
new Thread(new Runnable() {
public void run() {
File file = new File(filepath);
UploadUtil uploadUtil = new UploadUtil();
String result = uploadUtil.uploadFile(file, requestURL);
if (result.equals("OK")) {
Log.i("上传返回码", result + " ");
Message message = new Message();
message.obj = "上传完成";
handler.sendMessage(message);
} else {
Message message = new Message();
message.obj = "上传失败";
handler.sendMessage(message);
}
}
}).start();
标签:
原文地址:http://blog.csdn.net/aprilqq/article/details/51361040