博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
文件上传
阅读量:7211 次
发布时间:2019-06-29

本文共 2515 字,大约阅读时间需要 8 分钟。

1 package cn.servlet; 2  3 import java.io.File; 4 import java.io.IOException; 5 import java.util.List; 6 import java.util.UUID; 7  8 import javax.servlet.ServletException; 9 import javax.servlet.annotation.WebServlet;10 import javax.servlet.http.HttpServlet;11 import javax.servlet.http.HttpServletRequest;12 import javax.servlet.http.HttpServletResponse;13 14 import org.apache.commons.fileupload.FileItem;15 import org.apache.commons.fileupload.disk.DiskFileItemFactory;16 import org.apache.commons.fileupload.servlet.ServletFileUpload;17 18 @WebServlet(urlPatterns = "/up2")19 public class Up2Servlet extends HttpServlet {20     @Override21     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {22         req.setCharacterEncoding("UTF-8");23 24         DiskFileItemFactory disk = new DiskFileItemFactory();25         ServletFileUpload up = new ServletFileUpload(disk);26         // 如果你不知道用户上传多少个文件,则应该遍历27         try {28             List
list = up.parseRequest(req);29 FileItem item1 = list.get(0);30 String name = item1.getString("UTF-8");// 对于非文件,用于这种方式来获取用户提交的31 FileItem item2 = list.get(1);32 String age = item2.getString("UTF-8");33 FileItem item3 = list.get(2);34 String fileName = item3.getName();35 fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);36 // 对文件重名称37 String extName = fileName.substring(fileName.lastIndexOf(".") + 1);// abc.jpg38 // -=>39 // jpg40 String uuid = UUID.randomUUID().toString().replace("-", "");41 String newFileName = uuid + "." + extName;42 // 获取文件上传的真实的目录43 String realPath = getServletContext().getRealPath("/files");44 // 实现文件上传45 item3.write(new File(realPath, newFileName));46 // 将转发到show.jsp显示47 req.setAttribute("name", name);48 req.setAttribute("age", age);49 req.setAttribute("oldFileName", fileName);50 req.setAttribute("newFileName", newFileName);51 req.getRequestDispatcher("/jsps/show.jsp").forward(req, resp);52 } catch (Exception e) {53 e.printStackTrace();54 }55 56 }57 }

 

转载于:https://www.cnblogs.com/fujilong/p/5608430.html

你可能感兴趣的文章
ASP.NET MVC中,通用的异常处理
查看>>
Struts tiles入门(最最简单的例子)
查看>>
SpringBoot入门系列: Spring Boot的测试
查看>>
USequencer系列 |初识
查看>>
ARP攻击实战
查看>>
PowerDNS管理工具开发中学习到的DNS知识
查看>>
命令行出错Exception in thread "main" java.lang.UnsupportedClassVersionError:
查看>>
Vbs压缩备份文件夹以日期命名
查看>>
Myeclipse启动Tomcat服务器Address already in use: JVM_Bind
查看>>
svn服务器安装与配置
查看>>
deprecated conversion from string constant to ‘char*’
查看>>
SSH实战项目——在线商品拍卖网
查看>>
The Distribution File System
查看>>
Jvm原理剖析与调优之内存结构
查看>>
TortoiseSVN文件夹及文件图标不显示解决方法
查看>>
技术的价值--从实验到企业实施的关键性思想
查看>>
在VMWare中配置SQLServer2005集群 Step by Step(四)——集群安装
查看>>
实战:通过组策略为用户部署软件
查看>>
Fedora 17 安装视频
查看>>
基于zeromq的高性能分布式RPC框架Zerorpc 性能测试
查看>>