• JavaWeb:上传文件


    1.建普通maven项目,或者maven项目,这里以普通maven为例,区别的jar包的导入方式啦

    到中央仓库下载哦

    2.结构

    3.写fileservlet

    1. public class FileServlet extends HttpServlet {
    2. @Override
    3. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    4. //判断上传的文件是普通的表单还是带文件的表单(以表单方式提交)
    5. if(!ServletFileUpload.isMultipartContent(req)){
    6. return;//普通表单,终止方法运行
    7. }
    8. //创建文件上传后的保存路径
    9. String uploadPath=this.getServletContext().getRealPath("/WEB-INF/upload");
    10. File uploadFile=new File(uploadPath);
    11. if(!uploadFile.exists()){
    12. uploadFile.mkdir();//不存在,就创建这个目录
    13. }
    14. //缓存,临时文件放置
    15. String tmpPath=this.getServletContext().getRealPath("/WEB-INF/tmp");
    16. File file=new File(tmpPath);
    17. if(!file.exists()){
    18. file.mkdir();//不存在,就创建这个目录(临时)
    19. }
    20. //处理上传的文件,一般通过流获取
    21. try{
    22. //创建DiskFileItemFactory对象,处理文件上传限制 大小 路径
    23. DiskFileItemFactory factory=getDiskFileItemFactory(file);
    24. //获取ServletFileUpload
    25. ServletFileUpload upload=getServletFileUpload(factory);
    26. //处理上传的文件
    27. String msg=uploadParseRequest(upload,req,uploadPath);
    28. //servlet请求转发
    29. req.setAttribute("msg",msg);
    30. req.getRequestDispatcher("info.jsp").forward(req,resp);
    31. } catch (Exception e) {
    32. e.printStackTrace();
    33. }
    34. }
    35. private static String uploadParseRequest(ServletFileUpload upload, HttpServletRequest req, String uploadPath) throws FileUploadException, IOException {
    36. String msg="";
    37. List<FileItem>fileItems=upload.parseRequest(req);
    38. for(FileItem fileItem:fileItems){
    39. if(fileItem.isFormField()){
    40. String name=fileItem.getFieldName();
    41. String value=fileItem.getString("UTF-8");
    42. System.out.println(name+":"+value);
    43. }else {
    44. String uploadFileName=fileItem.getName();
    45. System.out.println("文件:"+uploadFileName);
    46. if(uploadFileName.trim().equals("")||uploadFileName==null){
    47. continue;
    48. }
    49. //获取文件名(/),和后缀名(.) /img.png
    50. String fileName=uploadFileName.substring(uploadFileName.lastIndexOf("/")+1);
    51. String fileExtName=uploadFileName.substring(uploadFileName.lastIndexOf(".")+1);
    52. System.out.println("文件消息:"+fileName+"类型"+fileExtName);
    53. //UUID 保证文件名唯一
    54. //UUID.randomUUID()随机生成一个通用码
    55. String uuidPath= UUID.randomUUID().toString();
    56. String realPath=uploadPath+"/"+uuidPath;
    57. File realPathFile=new File(realPath);
    58. if(!realPathFile.exists()){
    59. realPathFile.mkdir();
    60. }
    61. //获取上传文件的流
    62. InputStream inputStream=fileItem.getInputStream();
    63. FileOutputStream fos=new FileOutputStream(realPath+"/"+fileName);
    64. //缓冲区
    65. byte[]buffer=new byte[1024*1024];
    66. //判断读取完成?
    67. int len=0;
    68. while ((len=inputStream.read(buffer))>0){
    69. fos.write(buffer,0,len);
    70. }
    71. fos.close();
    72. inputStream.close();
    73. msg="success";
    74. fileItem.delete();
    75. }
    76. }
    77. return msg;
    78. }
    79. private static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
    80. ServletFileUpload upload=new ServletFileUpload(factory);
    81. //监听文件上传速度
    82. upload.setProgressListener(new ProgressListener() {
    83. @Override
    84. public void update(long l, long l1, int i) {
    85. System.out.println("总大小:"+l1+"已上传"+l);
    86. }
    87. });
    88. upload.setHeaderEncoding("UTF-8");
    89. upload.setFileSizeMax(1024*1024*10);
    90. //1024=1kb*1024=10M
    91. return upload;
    92. }
    93. private static DiskFileItemFactory getDiskFileItemFactory(File file) {
    94. DiskFileItemFactory factory=new DiskFileItemFactory();
    95. //设置缓冲区,文件大于缓冲区放到临时文件
    96. factory.setSizeThreshold(1024*1024);
    97. factory.setRepository(file);
    98. return factory;
    99. }
    100. @Override
    101. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    102. }
    103. }
    4.index.jsp
    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <html>
    3. <head>
    4. <title>Title</title>
    5. </head>
    6. <body>
    7. <form action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data" method="post">
    8. 上传用户:<input type="text" name="username"><br>
    9. <p><input type="file" name="file1"></p>
    10. <p><input type="file" name="file1"></p>
    11. <p><input type="submit">||<input type="reset"></p>
    12. </form>
    13. </body>
    14. </html>

    5.info

    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <html>
    3. <head>
    4. <title>Title</title>
    5. </head>
    6. <body>
    7. <%--上传文件大小有限制:get--%>
    8. ${msg}
    9. </body>
    10. </html>

  • 相关阅读:
    21.3 Python 使用DPKT分析数据包
    柔性数组(C语言)
    【JUC系列】同步工具类之ThreadLocal
    【华为机试真题 JAVA】求满足条件的最长子串的长度-100
    SpringBoot第48讲:SpringBoot定时任务 - Spring Schedule实现方式
    Vue3实现 SKU 规格
    [typescript] 引入js说找不到模块或其相应的类型声明
    (十一)VBA常用基础知识:worksheet的各种操作之sheet删除
    车路协同自动驾驶研究
    制作一个简单HTML游戏网页(HTML+CSS)仿龙之谷网络游戏官网
  • 原文地址:https://blog.csdn.net/2201_75903640/article/details/133659744