使用的是Servlet 3.0 新的特征标注(Annotaion)类描述部署,一些低版本的服务器需要使用标准依赖部署描述文件(web.xml)来部署,另外Part也是Java EE 6.0新增的类,Part是一个接口继承于javax.servlet.http,代表一部分表单项目接收来自multipart/form-data的POST的请求。

!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>上传文件</title> </head>
<body>
<div class="container">
<form action="upload.do" method="post" enctype="multipart/form-data">
<table>
<tr>
<td><label for="file">上传文件:</label></td>
<td><input type="file" id="file" name="picture" value=""/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="提交"/></td>
</tr>
</table>
</form>
</div>
</body>
</html>
@MultipartConfig
@WebServlet(name = "UploadServlet", urlPatterns = {"/upload.do"})
public class UploadServlet extends HttpServlet { private String contextPath; @Override
public void init() throws ServletException {
contextPath = getServletContext().getRealPath("/");
} protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
Part part = request.getPart("picture");
String fileName = getFileName(part);
writeTo(fileName, part); //forward到显示
request.setAttribute("fileName", fileName);
request.getRequestDispatcher("show.jsp").forward(request, response);
} //取得上传文件名
private String getFileName(Part part) {
String header = part.getHeader("Content-Disposition");
String fileName = header.substring(header.indexOf("filename=\"") + 10,
header.lastIndexOf("\""));
return fileName;
} //存储文件
private void writeTo(String fileName, Part part) throws IOException, FileNotFoundException {
InputStream in = part.getInputStream();
OutputStream out = new FileOutputStream(contextPath + fileName);
byte[] buffer = new byte[1024];
int length = -1;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
}

  

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>图片显示</h1>
<a href="${fileName}">${fileName}</a>
</body>
</html>

  

  

最新文章

  1. 由于C++编译器的分析机制所导致的声明问题
  2. JavaScript编码规范[百度]
  3. C++ 11 笔记 (四) : std::bind
  4. socket函数
  5. Codeforces 339E
  6. ngrok 本机代码部署外网访问神器(转)
  7. python处理时间--- datetime模块
  8. Android技术之-------电脑获取手机截图
  9. Web程序报错:Error instantiating servlet
  10. 通过iostat来查看linux硬盘IO性能|实例分析
  11. webapi 405 method not allowed
  12. 关于preg_match() / preg_replace()函数的一点小说明
  13. 各大引擎矩阵的矩阵存储方式 ----行矩阵 or 列矩阵
  14. MHA集群(gtid复制)和vip漂移
  15. Jquery 应用积累
  16. 思维导图_Python_内置函数
  17. MinnowBoard
  18. centos修改hostname
  19. Docker URL REST API访问设置
  20. FFMPEG基于内存的转码实例——输入输出视频均在内存

热门文章

  1. Markdown语法 中文版
  2. ubuntu用作开发办公平台的完美体验
  3. maven上传jar到nexus本地仓库
  4. Beta阶段发布说明
  5. Python 下载 tushare 数据,然后调用 C++ DLL 计算 wMA 存入本地 csv 文件再 python 读取
  6. ClassNotFoundException: org.apache.catalina.loader.DevLoader 自己摸索,丰衣足食
  7. ActiveMQ入门实例
  8. 记录下WIN下配置LINUX虚拟机及PYTHON环境
  9. NetBean 8 创建EJB
  10. Visifire Chart相关属性详解