android之文件上传

From:http://blog.csdn.net/mfsgss3432/article/details/8049607

 

文件上传


android中的文件上传使用的是post的提交方式。
通过httpwatcher抓一个文件上传时的包,可以更加好的明白下面的代码


//调用此方法时需要传递用户名,密码,文件路径


文件上传时,上传的内容一般分为两部分,一部分是普通字段,另一部分就是真正要上传的内容
下面通过注释对改程序的每行进行解释


android客户端代码:
public boolean upload(String username, String password, String filepath) throws Exception {
String boundary = "---------------------------7db1c523809b2";// 分割线
File file = new File(filepath);// 要上传的文件
Uri uri = Uri.parse(address);// 用来解析主机名和端口
URL url = new URL(address);// 用来开启连接
StringBuilder sb = new StringBuilder();// 用来拼装请求


// username字段
sb.append("--" + boundary + "\r\n");
sb.append("Content-Disposition: form-data; name=\"username\"" + "\r\n");
sb.append("\r\n");
sb.append(username + "\r\n");


// password字段
sb.append("--" + boundary + "\r\n");
sb.append("Content-Disposition: form-data; name=\"password\"" + "\r\n");
sb.append("\r\n");
sb.append(password + "\r\n");


// 文件部分
sb.append("--" + boundary + "\r\n");
sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + filepath + "\"" + "\r\n");
sb.append("Content-Type: application/octet-stream" + "\r\n");
sb.append("\r\n");


// 将开头和结尾部分转为字节数组,因为设置Content-Type时长度是字节长度
byte[] before = sb.toString().getBytes("UTF-8");
byte[] after = ("\r\n--" + boundary + "--\r\n").getBytes("UTF-8");

// 打开连接, 设置请求头
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
conn.setRequestProperty("Content-Length", before.length + file.length() + after.length + "");
conn.setRequestProperty("HOST", uri.getHost() + ":" + uri.getPort());// 192.168.1.100:8080
conn.setDoOutput(true);


// 获取输入输出流
OutputStream out = conn.getOutputStream();
FileInputStream fis = new FileInputStream(file);


// 将开头部分写出
out.write(before);


// 写出文件数据
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) != -1)
out.write(buf, 0, len);


// 将结尾部分写出
out.write(after);

fis.close();
out.close();
return conn.getResponseCode() == 200;
}


//javaweb服务器端代码,方便理解


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
System.out.println("POST:");

boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
try {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);// 从request中解析出若干表单项
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {// 遍历每一个表单项
   FileItem item = iter.next();
   if (item.isFormField()) {// 如果是普通字段
   String fieldName = item.getFieldName();// 获取字段名(name)
       String value = item.getString();// 获取字段值(value)
       System.out.println(fieldName + " = " + value);
   } else { // 不是普通字段, 就是上传文件
   String fieldName = item.getFieldName();// 获取字段名(name)
       String fileName = new File(item.getName()).getName();// 获取上传文件的文件名(有些浏览器可能会带着路径)
       System.out.println(fieldName + " = " + fileName);
       File uploadedFile = new File("F:/Upload", fileName);// 在Upload文件夹中创建文件
       item.write(uploadedFile);// 写出数据
   }
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("username = " + request.getParameter("username"));
System.out.println("password = " + request.getParameter("password"));
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值