美文网首页
学习文件上传

学习文件上传

作者: 小猪Harry | 来源:发表于2018-07-14 11:05 被阅读0次

    D:\Users\Think\IdeaProjects\FileUploadDemo\out\artifacts\FileUploadDemo_war_exploded
    该路径下放的是web文件夹下运行tomcat后的编译后输出文件。

    image.png
    image.png

    一个小例子,说明文件上传的原理。

    <%--
      Created by IntelliJ IDEA.
      User: Think
      Date: 2018/7/14
      Time: 0:06
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <title>$Title$</title>
      </head>
      <body>
      <%--form里面的配置需要注意--%>
      <form method="post" action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data">
        <img src="${pageContext.request.contextPath}/upload/${picpath}">
        <input type="text" name="text1">
        <input type="file" name="file1">
        <input type="submit" value="提交">
      </form>
      </body>
    </html>
    
    package com.zhu.servlet;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;
    import java.io.File;
    import java.io.IOException;
    import java.util.UUID;
    
    /**
     * Created by Think on 2018/7/14.
     */
    @WebServlet(name = "uploadServlet",urlPatterns = "/upload.do")
    @MultipartConfig      //这句话的配置必须加上
    public class uploadServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");
            String username = request.getParameter("text1");
            Part part = request.getPart("file1");
    
            System.out.println(username);
    
            String filename = part.getSubmittedFileName();
            System.out.println(filename);//此文件名还未加UUID
    
            UUID uuid = UUID.randomUUID();
    //        d:\Users\Think\IdeaProjects\FileUploadDemo\out\artifacts\FileUploadDemo_war_exploded 部署目录
    //        d:\Users\Think\IdeaProjects\FileUploadDemo\ 开发目录(源代码所在目录)
    
            String strPath = request.getServletContext().getRealPath("") + "upload" + File.separator;
            System.out.println(strPath);
    
            part.write(strPath+uuid+filename);
            request.getSession().setAttribute("picpath",uuid+filename);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        }
    }
    

    运行结果:


    image.png
    image.png

    相关文章

      网友评论

          本文标题:学习文件上传

          本文链接:https://www.haomeiwen.com/subject/sqkepftx.html