使用javax.servlet.http.Part类上传文件
2024-08-27 06:46:48
使用的是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>
最新文章
- 由于C++编译器的分析机制所导致的声明问题
- JavaScript编码规范[百度]
- C++ 11 笔记 (四) : std::bind
- socket函数
- Codeforces 339E
- ngrok 本机代码部署外网访问神器(转)
- python处理时间--- datetime模块
- Android技术之-------电脑获取手机截图
- Web程序报错:Error instantiating servlet
- 通过iostat来查看linux硬盘IO性能|实例分析
- webapi 405 method not allowed
- 关于preg_match() / preg_replace()函数的一点小说明
- 各大引擎矩阵的矩阵存储方式 ----行矩阵 or 列矩阵
- MHA集群(gtid复制)和vip漂移
- Jquery 应用积累
- 思维导图_Python_内置函数
- MinnowBoard
- centos修改hostname
- Docker URL REST API访问设置
- FFMPEG基于内存的转码实例——输入输出视频均在内存
热门文章
- Markdown语法 中文版
- ubuntu用作开发办公平台的完美体验
- maven上传jar到nexus本地仓库
- Beta阶段发布说明
- Python 下载 tushare 数据,然后调用 C++ DLL 计算 wMA 存入本地 csv 文件再 python 读取
- ClassNotFoundException: org.apache.catalina.loader.DevLoader 自己摸索,丰衣足食
- ActiveMQ入门实例
- 记录下WIN下配置LINUX虚拟机及PYTHON环境
- NetBean 8 创建EJB
- Visifire Chart相关属性详解