ContextType(MIME) 与 Java文件上传/下载
ContextType(MIME)
ContextType 是 MIME(Multipurpose Internet Mail Extensions,媒体类型,多用途因特网邮件扩展)在HTTP代表传输信息的类型的字段。不同的 ContextType 代表不同的类型,有一些常用的 ContextType。
MIME 类型的语法type/subtype,它在 IETF RFC 6838 中进行了定义和标准化,语法由顶级类型与子类型构成,中间由一个’/'组成,如 text/html 代表一个 html 的文本类型
Text
text 顶级类型用于发送内容主要是文本形式
常用类型:
- text/plain :纯文本格式,是纯文本的泛型子类型
- text/html : HTML格式
- text/xml : XML格式
Image
image 顶级类型表示内容指定了一个过更多的单个图像,子类型为特定的图像命名格式
常用类型:
- image/gif :gif图片格式
- image/jpeg :jpg图片格式
- image/png:png图片格式
Audio
audio 顶级类型表示内容包含音频数据,子类型命名特定的音频格式
Video
video 顶级类型表示内容指定了一个视频(随时间变化的图像),可能有颜色和协调声音,更确切地说,“视频”这个词是用它最一般的意义上的而不是引用任何特定的技术或格式不排除子类型,如编码的动画图简洁。
Application
application 顶级类型常用途类型名称包括但不限于文件传输、电子表格、演示文稿、调度数据和“活动”语言(计算)的形式
常用类型:
- application/xhtml+xml :XHTML格式
- application/xml: XML数据格式
- application/atom+xml :Atom XML聚合格式
- application/json: JSON数据格式
- application/pdf:pdf格式
- application/msword : Word文档格式
- application/octet-stream : 二进制流数据(如常见的文件下载)
- application/x-www-form-urlencoded : <form encType="">中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)
Multipart 和 Message
multipart 和 message 是复合类型,也就是说,它们提供了封装零个或多个对象的方法,每个对象都是独立的媒体类型。
multipart和message的所有子类型必须符合 [RFC 2046] 中规定的语法规则和其他要求,并由 [RFC 6532] 章节3.5修正。
- multipart/form-data : 需要在表单中进行文件上传时,就需要使用该格式
上传/下载
处理文件上传/下载 Java 代码(未处理细节,简单的上传下载以及移除;如重名(UUID)等)
上传
/**
* 文件上传 使用第三方jar包:commons-fileupload 和 commons-io
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void upload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ReturnEntity returnEntity = null;
//判断是否是多段数据
if (ServletFileUpload.isMultipartContent(req)) {
//创建FIleItemFactory工厂实现类
FileItemFactory fileItemFactory = new DiskFileItemFactory();
//创建用于解析上传数据的工具类ServletFileUpload类
ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
//解析上传的数据,得到表单项
try {
List<FileItem> fileItems = servletFileUpload.parseRequest(req);
for (FileItem fileItem : fileItems) {
System.out.println(fileItem);
if (fileItem.isFormField()){
System.out.println("name值:" + fileItem.getFieldName());
System.out.println("value值:" + fileItem.getString("UTF-8"));
} else {
System.out.println("name值:" + fileItem.getFieldName());
System.out.println("value值:" + fileItem.getName());
fileItem.write(new File(getServletContext().getRealPath("/")+fileItem.getName()));
returnEntity = new ReturnEntity(CodeStatus.UPLOAD_SUCCESS.getCode(), CodeStatus.UPLOAD_SUCCESS.getMsg(), null);
}
}
} catch (Exception e) {
e.printStackTrace();
returnEntity = new ReturnEntity(CodeStatus.UPLOAD_FAILED.getCode(), CodeStatus.UPLOAD_FAILED.getMsg(), null);
}
} else {
returnEntity = new ReturnEntity(CodeStatus.UPLOAD_FAILED.getCode(), CodeStatus.UPLOAD_FAILED.getMsg(), null);
}
// 返回结果
resp.setContentType("application/json;charset=utf-8");
PrintWriter writer = resp.getWriter();
try {
writer.write(JSON.toJSONString(returnEntity));
} finally {
writer.flush();
writer.close();
}
}
下载
/**
* 文件下载
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void download(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取请求资源路径
String filePath = req.getParameter("filePath");
//获取Servlet上限文
ServletContext servletContext = getServletContext();
//获取要下载的文件类型
String mimeType = servletContext.getMimeType(filePath);
System.out.println("mimeType = " + mimeType);
//在回传前,通过响应头告诉客户端返回的数据类型
resp.setContentType(mimeType);
//告诉客户端收到的数据是用于下载使用(通过响应头)
if (req.getHeader("User-Agent").contains("Firefox")) {
//火狐浏览器 Base64
resp.setHeader("Content-Disposition", "attachment; filename==?UTF-8?B?" + new BASE64Encoder().encode(filePath.getBytes("UTF-8")) + "?=");
} else {
//谷歌 IE URLEncoder
resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filePath, "UTF-8"));
}
//获取传输文件流
InputStream resourceAsStream = servletContext.getResourceAsStream(filePath);//要上传的文件路径 从工程目录下获取资源
//获取回传的输出流
ServletOutputStream outputStream = resp.getOutputStream();
//输出文件
try {
byte[] data = new byte[1024 * 8];
int len = 0;
while ((len = resourceAsStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
} finally {
resourceAsStream.close();
outputStream.flush();
outputStream.close();
}
// IOUtils.copy(resourceAsStream, outputStream); // 第三方jar包:commons-io-2.11.0.jar
System.out.println("download '" + filePath + "' completion");
}
删除
/**
* 删除文件
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void removeFile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取删除路径
String removePath = req.getParameter("removePath");
String realPath = getServletContext().getRealPath(removePath);
// 获取文件
File file = new File(realPath);
boolean success = false;
if (file.isFile()) {
// 删除
success = file.delete();
}
// 返回信息
ReturnEntity returnEntity = null;
if (success) {
// 删除成功
returnEntity = new ReturnEntity(CodeStatus.SUCCESS.getCode(), CodeStatus.SUCCESS.getMsg(), null);
} else {
returnEntity = new ReturnEntity(CodeStatus.FAILED.getCode(), CodeStatus.FAILED.getMsg(), null);
}
PrintWriter writer = resp.getWriter();
try {
writer.write(JSON.toJSONString(returnEntity));
} finally {
writer.flush();
writer.close();
}
}