JSP文件上传
来源:互联网 发布:二叉树的深度 java 编辑:程序博客网 时间:2024/06/09 16:37
概述:
文件上传是网站中很常用的一个功能,下面是一个文件上传的基本demo。
由于是使用的新版jar包,所以需要依赖以下几个jar包:
catalina.jar
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
public class UpLoadServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * 该方法用于文件上传 * @jar catalina.jar commons-fileupload-1.3.1.jar commons-io-2.4.jar */ public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); request.setCharacterEncoding("UTF-8"); /* * 文件上传逻辑 */ //创建DiskFileItemFactory对象,为解析器提供解析时的一些缺省配置 DiskFileItemFactory dfif = new DiskFileItemFactory(); //创建解析器 ServletFileUpload sfu = new ServletFileUpload(dfif); //使用解析器解析分析器 try { //解析request请求 List<FileItem> items = sfu.parseRequest(request); for(FileItem item : items) { //如果是普通表单类 if(item.isFormField()) { continue; } //执行上传文件动作 //根据servlet上下文获得服务器中实际物理路径 //此处可以更改为其他另存为的路径 String path = getServletContext().getRealPath("/upload"); //获取文件名 String fileName = item.getName(); //获取文件后缀 String fileSuffix = fileName.substring(fileName.lastIndexOf(".")); //设置当前系统时间毫秒数的值为文件名(无需考虑同步,几率极其低) String newName = Calendar.getInstance().getTimeInMillis()+fileSuffix; //File.separator是获取一个兼容操作系统路径的"/" File file = new File(path+File.separator+newName); try { //写入文件 item.write(file); } catch (Exception e) { e.printStackTrace(); } } } catch (FileUploadException e) { e.printStackTrace(); } }}
jsp页面代码
<!-- enctype="multipart/form-data"表示不对上传的消息进行编码 --> <form action="upload.do" enctype="multipart/form-data" method="post"> <input type="file" name="fileName"> <input type="submit" value="提交">
这里注意:上传后的文件是上传到TomCat中该的项目的目录中的upload文件夹,如果将TomCat上项目移除,上传的文件也会随之消失。
0 0
- JSP 进行文件上传。JSP文件上传
- jsp文件上传
- jsp文件上传
- jsp文件上传处理
- jsp实现文件上传
- jsp上传文件
- JSP mySmartUpload上传文件
- JSP Uploader上传文件
- jsp上传文件
- 文件上传(JSP)
- 使用jsp上传文件
- Jsp 上传文件
- 上传文件 JSP+java
- jsp上传文件
- jsp实现文件上传
- JSP smartupload 文件上传
- 使用jsp上传文件
- jsp单文件上传
- 轻量级 js取色器 JSColor
- LeetCode 题解(221) : Binary Tree Level Order Traversal
- Leetcode NO.136 Single Number
- C++类的构造函数和析构函数
- 技术面试(算法)
- JSP文件上传
- The requested URL /nagios/cgi-bin/statusmap.cgi was not found on this server
- *LeetCode-Search in Rotated Sorted Array II
- *LeetCode-Trapping Rain Water
- js显示当前年月日
- 关于Co-segmentation
- Java程序中运行命令行命令
- C++实现RTMP协议发送H.264编码及AAC编码的音视频,摄像头直播
- 窥探Unity5渲染内部之解析UnityShaderVariables.cginc