在项目中我们有时候需要使用到其他第三方的api,而有些api要求我们上传文件,search一下,下面将结果记录一下喽!
含义 ENCTYPE="multipart/form-data" 说明:
通过 http 协议上传文件 rfc1867协议概述,jsp 应用举例,客户端发送内容构造
1、概述在最初的 http 协议中,没有上传文件方面的功能。 rfc1867 (http://www.ietf.org/rfc/rfc1867.txt) 为 http 协议添加了这个功能。客户端的浏览器,如 Microsoft IE, Mozila, Opera 等,按照此规范将用户指定的文件发送到服务器。服务器端的网页程序,如 php, asp, jsp 等,可以按照此规范,解析出用户发送来的文件。Microsoft IE, Mozila, Opera 已经支持此协议,在网页中使用一个特殊的 form 就可以发送文件。绝大部分 http server ,包括 tomcat ,已经支持此协议,可接受发送来的文件。各种网页程序,如 php, asp, jsp 中,对于上传文件已经做了很好的封装。
2、上传文件实例,jsp例子:
<form action="gerry/publish/file" enctype="multipart/form-data" method="post">
file:<input type="file" name="file"/><br/>
<input type="submit" value="submit"/>
</form>
如果上传文件,我们必须将enctype设置成"multipart/form-data",表示我们上传的是一个二进制数据流。
3、Servlet中解析这个请求
boolean isMultipart = ServletFileUpload.isMultipartContent(req);
if (isMultipart) {
// 构造一个文件上传处理对象
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory); Iterator items;
try {
// 解析表单中提交的所有文件内容
items = upload.parseRequest(req).iterator();
while (items.hasNext()) {
FileItem item = (FileItem) items.next();
System.out.println(item.getFieldName());
System.out.println(item.isFormField());
System.out.println(item.getString()); if (!item.isFormField()) {
// 取出上传文件的文件名称
String name = item.getName();
// 取得上传文件以后的存储路径
String fileName = name.substring(name.lastIndexOf('\\') + 1, name.length());
// 上传文件以后的存储路径
String path = req.getRealPath("file") + File.separatorChar + fileName; // 上传文件
File uploaderFile = new File(path);
item.write(uploaderFile);
}
}
} catch (Exception e) {
resp.getOutputStream().write(("throw exception " + e.getMessage()).getBytes());
}
} else {
resp.getOutputStream().write("is not this file upload".getBytes());
}
通过ServletFileUpload的parseRequest方法可以将文件流和非文件流全部解析出来。不用考虑HttpServletRequest中的数据流格式。
4、Spring中解析这个请求
在Spring中我们可以直接通过MultipartFile来获取请求中的文件流信息。
@RequestMapping(value = "/gerry/publish/file")
@ResponseBody
public String upload1(MultipartFile file) {
String originalFileName = file.getOriginalFilename();
String fileName = file.getName();
System.out.println(originalFileName);
System.out.println(fileName);
System.out.println(file.getContentType());
try {
MyHttpClient.addPic(file.getBytes());
} catch (Exception e) {
return "failure, the exception msg is: " + e.getMessage();
}
return "success";
}
5、代码中构造HttpClient请求,传输文件
/**
* 传输文件流bs
*
* @param bs
* 要传输的文件流
*/
public static void addPic(byte[] bs) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
entity.addPart("pic", new ByteArrayBody(bs, "pic"));
try {
// 添加其他的参数,可以是多个/零个
entity.addPart("name", new StringBody("liuming92"));
} catch (UnsupportedEncodingException e1) {
throw new RuntimeException(e1);
}
httpPost.setEntity(entity);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse != null) {
String result = EntityUtils.toString(httpResponse.getEntity());
System.out.println(result);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
到这里位置,java中上传文件以及向第三方传输文件都实现啦。