您的位置:首页 > 其它

室友画圣诞树的时候,我卷了一把文件上传和下载

2021-12-22 08:30 597 查看

🏇 小 木 来 了 \textcolor{Orange}{小木来了} 小木来了
🍣 圣 诞 树 火 了 \textcolor{green}{圣诞树火了} 圣诞树火了, 但 怎 20000 么 忘 了 文 件 上 传 呢 \textcolor{red}{但怎么忘了文件上传呢} 但怎么忘了文件上传呢🍣
🍣 我 可 以 将 许 多 的 图 片 文 档 等 都 可 以 进 行 上 传 \textcolor{green}{我可以将许多的图片文档等都可以进行上传} 我可以将许多的图片文档等都可以进行上传 但 这 岂 不 更 爽 \textcolor{red}{但这岂不更爽} 但这岂不更爽🍣
🙏 博 主 也 在 学 习 阶 段 , 如 若 发 现 问 题 , 请 告 知 , 非 常 感 谢 \textcolor{Orange}{博主也在学习阶段,如若发现问题,请告知,非常感谢} 博主也在学习阶段,如若发现问题,请告知,非常感谢💗
欢迎各位小伙伴😄关注👍点赞⭐️收藏📝留言

文件上传和下载

  • 2.4 pom.xml导入需要的依赖
  • 2.5 index.jsp
  • 2.6 info.jsp
  • 2.7 FileServlet
  • 2.8 配置Servlet
  • 2.9 测试结果
  • 3. SpringMVC文件上传和下载
  • 1. 文件传输原理及介绍

    2. JavaWeb文件上传

    2.1我们用一个新的方式创建项目

    空项目会直接弹出框

    把jdk版本设置好

    点击确定后是比较干净的,啥都不会,不要慌,点击file->new->module。之后就和之前做过的一样了

    创建model:file,配置tomcat运行保证没有错误

    2.2 导包

    可以选择去

    maven
    仓库中下,也可以在官网上搜出来然后复制到项目中,我们创建一个文件夹lib,然后如果从外面复制到项目中需要右键点击
    add as library
    添加到内库中

    • 上述只是讲一个新建项目的方式,我后面还是按照之前的用maven进行了一个项目完成

    2.3 实用类介绍

    • 文件上传的注意事项 为保证服务器安全,上传文件应该放在外界无法直接访问的目录下,比如放在WEB-INF目录下。
    • 为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名, 加一个时间戳
    • UUID
    • md5
    • 自己写位运算算法
  • 要限制上传文件的最大值
  • 可以限制上传文件的类型,在收到上传文件名时,判断后缀名是否合法。
  • 需要用到的类详解

    ServletFileUploa
    d负责处理上传的文件数据,并将表单中每个输入项封账成一个
    fileItem
    对象,在使用
    ServletFileUpload
    对象解析请求时需要
    DiskFileItemFactory
    对象。所以,我们需要在进行解析工作前构造好
    DiskFileItemFactory
    对象,通过
    ServletFileUpload
    对象的构造方法或
    setFileItemFactory()
    方法设置
    ServletFileUpload
    对象的
    fileItemFactory
    属性。

    FileItem类

    在HTML页面input必须有

    <input type="file" name = "filename">

    表单中如果包含一个文件上传输入项的话,这个表单的enctype属性就必须设置为multipart/form-data

    • 常用方法介绍
    //isFromField方法用于判断FileItem类对象封装的数据是一个普通文本表单还是一个文件表单,如果是普通表单就返回true,否则返回false
    boolean isFormField();
    //getFieldName方法用于返回表单标签name属性的值
    String getFieldName();
    //getString方法用于将FileItem对象中保存的数据流内容以一个字符串返回
    String getString();
    //getName方法用于获得文件上传字段中的文件名
    String getName();
    //以流的形式返回上传文件的数据内容
    InputStream getInputStream();
    //delete方法用来清空FileItem类对象中存放的主体内容。如果主题内容被保存在临时文件中,delete方法将删除该临时文件
    void delete();
    ServletFileUpload类

    ServletFileUpload
    负责处理上传的文件数据,并将表单中每个输入项封装成一个
    FileItem
    对象中,使用其
    parseRequest(HttpServletRequest)
    方法可以将通过表单中每一个HTML标签提交的数据封装成一个
    FIleItem
    对象,然后以
    list
    列表的形式返回。使用该方法处理上传文件简单易用

    2.4 pom.xml导入需要的依赖

    <!--Servlet 依赖-->
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    </dependency>
    <!--JSP依赖-->
    <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.3</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
    </dependency>

    2.5 index.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>$Title$</title>
    </head>
    <body>
    <%--通过表单上传文件;
    get:上传文件大小有限制
    post:上传文件大小没有限制
    ${pageContext.request.contextPath}获取服务器当前路径
    --%>
    <form action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data" method="post">
    上传用户:<input type="text" name="username"><br/>
    <p><input type="file" name="file1"></p>
    <p><input type="file" name="file1"></p>
    
    <p><input type="submit"> | <input type="reset"></p>
    
    </form>
    </body>
    </html>

    2.6 info.jsp

    该页面主要用于接受message

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>Title</title>
    </head>
    <body>
    <%=request.getAttribute("msg")%>
    </body>
    </html>

    2.7 FileServlet

    这里的包一定要注意不要导错了。另外这里使用了封装的方法让结构看起来更简洁

    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.ProgressListener;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.util.List;
    import java.util.UUID;
    
    public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doPost(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //判断上传的文件是普通表单还是带文件的表单
    if (!ServletFileUpload.isMultipartContent(req)) {
    return;//终止方法运行,说明这是一个普通的表单
    }
    
    //创建上传文件的保存路径,建议在WEB-INF路径下,安全,用户无法直接访问上传的文件
    //获得全局的上下文,地址
    String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
    File uploadFile = new File(uploadPath);
    if (!uploadFile.exists()) {
    uploadFile.mkdir();//创建这个目录
    }
    //缓存,临时文件
    //临时文件,假如文件超过了预期的大小,我们就把他放到一个临时文件中,过几天激动删除,或者提醒用户转存为永久
    String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp");
    File tmpFile = new File(tmpPath);
    if (!tmpFile.exists()) {
    tmpFile.mkdir();//创建这个目录
    }
    //处理上传的文件,一般需要通过流来获取,我们可以使用request.getInputStream(),原生态的文件上传流获取,
    //上面的太麻烦,建议使用APache的文件上传组件来实现,common-fileupload,它需要依赖于commons-io组件
    try {
    //1.创建DiskFileItemFactory对象,处理文件上传路径或者大小限制的
    DiskFileItemFactory factory = getDiskFileItemFactory(tmpFile);
    //2.获取ServletFileUpload
    ServletFileUpload upload = getServletFileUpload(factory);
    //3.处理上传文件
    String msg = uploadParseRequest(upload, req, uploadPath);
    //servlet请求转发消息
    req.setAttribute("msg", msg);
    req.getRequestDispatcher("info.jsp").forward(req, resp);
    } catch (FileUploadException e) {
    e.printStackTrace();
    }
    
    }
    
    public static DiskFileItemFactory getDiskFileItemFactory(File tmpFile) {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    //通过这个工厂设置一个缓冲区,当上传的文件大于这个缓冲区的时候,将他放到临时文件中
    //可以设可以不设
    factory.setSizeThreshold(1024 * 1024);
    factory.setRepository(tmpFile);
    return factory;
    }
    
    public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
    //2.获取ServletFileUpload
    ServletFileUpload upload = new ServletFileUpload(factory);
    //可以设,可以不设
    //监听文件上传进度
    upload.setProgressListener(new ProgressListener() {
    //pContentLength:文件大小
    //pBytesRead:已经读取到的文件大小
    @Override
    public void update(long pBytesRead, long pContentLength, int pItems) {
    System.out.println("总大小:" + pContentLength + "已上传" + pBytesRead);
    }
    });
    //处理乱码问题
    upload.setHeaderEncoding("UTF-8");
    //设置单个文件的最大值
    upload.setFileSizeMax(1024 * 1024 * 10);
    //设置总共能够上传的文件的大小
    //1024 = 1kb * 1024 = 1M * 10 = 10M
    upload.setSizeMax(1024 * 1024 * 10);
    return upload;
    }
    
    public static String uploadParseRequest(ServletFileUpload upload, HttpServletRequest req, String uploadPath) throws FileUploadException, IOException {
    String msg = "";
    //3.处理上传文件
    //把前端请求解析,封装成一个FileItem对象,需要从ServletFileUpload对象中获取
    List<FileItem> fileItems = upload.parseRequest(req);
    //每一个表单对象
    for (FileItem fileItem : fileItems) {
    //判断上传的文件是普通的表单还是带文件的表单
    if (fileItem.isFormField()) {
    //getFieldName()指的是前端表单控件的name
    String name = fileItem.getFieldName();
    String value = fileItem.getString("UTF-8");//处理乱码
    System.out.println(name + ":" + value);
    } else {  //文件的情况
    //=====处理文件
    //拿到文件名字
    String uploadFileName = fileItem.getName();
    System.out.println("上传的文件名:" + uploadFileName);
    if (uploadFileName.trim().equals("") || uploadFileName == null) {
    continue;
    }
    //获得文件上传的文件名和后缀名;/images/boys/dajie.jpg  下面这块不是必须的
    String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
    String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
    
    //如果文件后缀名fileExtName不是我们所需要的就直接return,不处理,告诉用户文件类型不对
    
    System.out.println("文件信息【件名:" + fileName + "---文件类型" + fileExtName + "】");
    //可以使用UUID(唯一识别的通用码),保证文件名唯一
    //UUID.randomUUID(),随机生成一个唯一识别的通用码
    //网络传输中的东西,都需要序列化,
    //比如:POJO,实体类,如果想要在多个电脑上运行,需要进行传输===>需要把对象序列化
    //implements Serializable :标记接口,JVM--> java栈 本地方法栈 ; native---》C++
    String uuidPath = UUID.randomUUID().toString();
    //===处理文件结束
    
    //=====存放地址
    //存到哪?uploadPath
    //文件真实存在的路径realPath
    String realPath = uploadPath + "/" + uuidPath;
    //给每个文件创建一个对应的文件夹
    File realPathFile = new File(realPath);
    if (!realPathFile.exists()) {
    realPathFile.mkdir();
    }
    //=====存放地址完毕
    
    //=====文件传输
    //获得文件上传的流
    InputStream inputStream = fileItem.getInputStream();
    //创建一个文件输出流
    //realPath = 真实的文件夹
    //差了一个文件,加上输出的文件的名字+"/" +uuidFileName
    FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);
    //创建一个缓冲区
    byte[] buffer = new byte[1024 * 1024];
    //判断是否读取完毕
    int len = 0;
    //如果大于0说明还存在数据
    while ((len = inputStream.read(buffer)) > 0) {
    fos.write(buffer, 0, len);
    }
    //关闭流
    fos.close();
    inputStream.close();
    msg = "文件上传成功!";
    fileItem.delete();//上传成功,清楚临时文件
    }
    }
    return msg;
    }
    }

    2.8 配置Servlet

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    version="4.0">
    <servlet>
    <servlet-name>FileServlet</servlet-name>
    <servlet-class>com.hxl.servlet.FileServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>FileServlet</servlet-name>
    <url-pattern>/upload.do</url-pattern>
    </servlet-mapping>
    
    </web-app>

    2.9 测试结果

    3. SpringMVC文件上传和下载

    3.1 上传

    在controller中有两种方式

    新建一个module,一套流程整体下来。测试能运行即可

    − − > 导 入 j a r 包 \textcolor{OrangeRed}{--> 导入jar包} −−>导入jar包💻

    <!--文件上传-->
    <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
    </dependency>
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    </dependency>

    − − > i n d e x . j s p \textcolor{OrangeRed}{--> index.jsp} −−>index.jsp💻

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>文件上传和下载</title>
    </head>
    <body>
    <form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
    <input type="file" name="file"/>
    <input type="submit" value="upload">
    </form>
    </body>
    </html>

    − − > a p p l i c a t i o n C o n t e x t . x m l 中 配 置 b e a n \textcolor{OrangeRed}{--> applicationContext.xml中配置bean} −−>applicationContext.xml中配置bean💻

    <!--文件上传配置-->
    <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
    <property name="defaultEncoding" value="utf-8"/>
    <!-- 上传文件大小上限,单位为字节(10485760=10M) -->
    <property name="maxUploadSize" value="10485760"/>
    <property name="maxInMemorySize" value="40960"/>
    </bean>

    − − > F i l e C o n t r o l l e r \textcolor{OrangeRed}{--> FileController} −−>FileController💻

    package com.hxl.controller;
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.commons.CommonsMultipartFile;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.*;
    
    @RestController
    public class FileController {
    //@RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
    //批量上传CommonsMultipartFile则为数组即可
    @RequestMapping("/upload")
    public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {
    
    //获取文件名 : file.getOriginalFilename();
    String uploadFileName = file.getOriginalFilename();
    
    //如果文件名为空,直接回到首页!
    if ("".equals(uploadFileName)){
    return "redirect:/index.jsp";
    }
    System.out.println("上传文件名 : "+uploadFileName);
    
    //上传路径保存设置
    String path = request.getServletContext().getRealPath("/upload");
    //如果路径不存在,创建一个
    File realPath = new File(path);
    if (!realPath.exists()){
    realPath.mkdir();
    }
    System.out.println("上传文件保存地址:"+realPath);
    
    InputStream is = file.getInputStream(); //文件输入流
    OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //文件输出流
    
    //读取写出
    int len=0;
    byte[] buffer = new byte[1024];
    while ((len=is.read(buffer))!=-1){
    os.write(buffer,0,len);
    os.flush();
    }
    os.close();
    is.close();
    return "redirect:/index.jsp";
    }
    
    /*
    * 采用file.Transto 来保存上传的文件
    */
    @RequestMapping("/upload2")
    public String  fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
    
    //上传路径保存设置
    String path = request.getServletContext().getRealPath("/upload");
    File realPath = new File(path);
    if (!realPath.exists()){
    realPath.mkdir();
    }
    //上传文件地址
    System.out.println("上传文件保存地址:"+realPath);
    
    //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
    file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
    
    return "redirect:/index.jsp";
    }
    }

    − − > 测 试 : \textcolor{OrangeRed}{--> 测试:} −−>测试:💻

    3.2 下载

    1、设置 response 响应头

    2、读取文件 – InputStream

    3、写出文件 – OutputStream

    4、执行操作

    5、关闭流 (先开后关)

    − − > i n d e x . j s p \textcolor{OrangeRed}{--> index.jsp} −−>index.jsp💻

    <a href="${pageContext.request.contextPath}/download">点击下载</a>

    − − > 增 加 一 个 u p l o a d 文 件 \textcolor{OrangeRed}{-->增加一个upload文件} −−>增加一个upload文件💻

    并且把要下载的图片弄进去

    − − > c o n t r o l l e r \textcolor{OrangeRed}{-->controller} −−>controller💻

    @RequestMapping(value="/download")
    public String downloads(HttpServletResponse response , HttpServletRequest request) throws Exception{
    //要下载的图片地址
    String  path = request.getServletContext().getRealPath("/upload");
    //String  fileName = "你想要下载的文件,要加上后缀";
    String  fileName = "1.jpg";
    
    //1、设置response 响应头
    response.reset(); //设置页面不缓存,清空buffer
    response.setCharacterEncoding("UTF-8"); //字符编码
    response.setContentType("multipart/form-data"); //二进制传输数据
    //设置响应头
    response.setHeader("Content-Disposition",
    "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
    
    File file = new File(path,fileName);
    //2、 读取文件--输入流
    InputStream input=new FileInputStream(file);
    //3、 写出文件--输出流
    OutputStream out = response.getOutputStream();
    
    byte[] buff =new byte[1024];
    int index=0;
    //4、执行 写出操作
    while((index= input.read(buff))!= -1){
    out.write(buff, 0, index);
    out.flush();
    }
    out.close();
    input.close();
    return "ok";
    }

    − − > 测 试 : \textcolor{OrangeRed}{-->测试:} −−>测试:💻

    内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签: