网络上传和下载文件功能实现步骤总结

文件上传下载步骤

JavaWeb项目

1. 导包

导入commons-iocommons-fileupload jar包

2. 前端页面

action:页面请求,需和web.xml中匹配

method:设置为post,没有文件大小限制

enctype:值为multipart/form-data用于识别是否为文件表单还是普通文本表单

<form action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data" method="post">
    <input type="file" name="file1">
    <br>
    <input type="file" name="file2">
    <br>
    <input type="submit">
    <br>
</form>

3. 注册web.xml

    <servlet>
        <servlet-name>FileUploadServlet</servlet-name>
        <servlet-class>com.juyss.servlet.FileUploadServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FileUploadServlet</servlet-name>
        <url-pattern>/upload.do</url-pattern>
    </servlet-mapping>

4. 编写Servlet

实现步骤

  1. 判断表单为普通文本表单还是文件表单

  2. 创建上传文件的保存根路径

  3. 创建临时文件的保存根路径

  4. 获取FileItem对象

    ​ 需要ServletFileUpload对象

    ​ 需要用到DiskFileItemFactory对象,用于处理上传路径和限制文件大小

  5. 通过FileItem对象获取文件名,文件后缀

  6. 使用UUID创建唯一保存路径

  7. 使用fileItem.getInputStream()获取文件输入流

  8. 创建文件输出流FileOutputStream fos = new FileOutputStream(savePath + "/" + fileName)

  9. 关闭流资源,同时删除临时文件fileItem.delete()

public class FileUploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("进入了FileUploadServlet.class");

        //判断表单是否为带有文件的表单
        if (!ServletFileUpload.isMultipartContent(request)) {
            return; //终止方法运行
        }

        //定义文件上传后保存的根路径
        String rootPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        File rootFile = new File(rootPath);
        if (!rootFile.exists()) {
            rootFile.mkdir();
        }

        //定义文件缓存路径
        String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
        File tempFile = new File(tempPath);
        if (!tempFile.exists()) {
            tempFile.mkdir();
        }

        //创建DiskFileItemFactory对象,处理上传路径和限制文件大小
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(1024 * 1024, tempFile);

        //创建ServletFileUpload对象
        ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);

        //获取FileItem对象
        List<FileItem> fileItems = null;
        try {
            fileItems = servletFileUpload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        if (fileItems==null){
            System.out.println("fileItem空指针");
            return;
        }
        Iterator<FileItem> iterator = fileItems.iterator();

        //遍历fileItems集合
        while (iterator.hasNext()) {
            FileItem fileItem = iterator.next();
            if (fileItem.isFormField()) {//是普通文本表单
                continue; //跳出循环
            } else {//是文件表单
                //获取文件字段名,标签中name属性的值
                String fieldName = fileItem.getFieldName();
                //获取文件上传字段中的文件名,一般来说为为文件名(不包含路径信息),在opera浏览器中可能会包含文件路径信息
                String name = fileItem.getName();
                System.out.println("文件字段名:"+fieldName);
                System.out.println("文件名:"+name);

                //判断文件名是否合法
                if (name.trim().equals("") || name == null) {
                    continue;
                }

                //获取文件名和文件后缀

                String fileName; //文件名
                if (name.contains("/")){ //判断name是否包含路径信息
                    fileName = name.substring(name.lastIndexOf("/"));
                }else{
                    fileName = name;
                }

                String fileExtension = fileName.substring(fileName.indexOf(".") + 1);//获取文件后缀
                System.out.println("文件名:" + fileName);
                System.out.println("文件类型:" + fileExtension);
                //获取随机UUID
                String uuid = UUID.randomUUID().toString();

                //使用uuid创建唯一的文件夹作为文件存放路径
                String savePath = rootPath + "/" + uuid; //文件存放路径
                File savePathFile = new File(savePath);
                if (!savePathFile.exists()) { //路径不存在就创建
                    savePathFile.mkdir();
                }

                //获取输入流读取上传的文件
                InputStream is = fileItem.getInputStream();

                //用输出流保存到本地
                FileOutputStream fos = new FileOutputStream(savePath + "/" + fileName);

                int len;
                byte[] bytes = new byte[1024 * 1024];
                while((len = is.read(bytes))!=-1){
                    fos.write(bytes,0,len);
                }

                fos.close();
                is.close();
                //删除临时文件
                fileItem.delete();
            }
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

SpringBoot项目

文件上传

1. 引入web支持和模板引擎

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

2. 编写控制器

@RestController
@RequestMapping("/file")
public class FileController {

    /**
     * 文件上传控制器
     * @param file 上传的文件
     * @return 上传信息
     */
    @RequestMapping("/upload")
    public String upload(MultipartFile file){ //变量名需要与前端页面的file类型的name值一致

        //判断传入文件是否为空
        if (file == null || file.isEmpty()) {
            return "未选择需上传的文件";
        }

        //定义文件保存位置(绝对路径)
        String filePath = new File("D:\WorkSpace\Demo-Project\atguigu-Advanced\fileupload\src\main\resources\upload").getPath();
        //判断文件路径是否存在,不存在就创建路径
        File fileUpload = new File(filePath);
        if (!fileUpload.exists()) {
            fileUpload.mkdirs();
        }

        //创建文件对象,指定文件保存路径和文件名
        fileUpload = new File(filePath, Objects.requireNonNull(file.getOriginalFilename()));

        //判断是否存在同名文件
        if (fileUpload.exists()) {
            return "上传的文件已存在";
        }

        //保存文件
        try {
            file.transferTo(fileUpload);
        } catch (IOException e) {
            e.printStackTrace();
            return "上传到服务器失败";
        }

        //返回信息
        return file.getOriginalFilename()+"文件上传成功";
    }

}

3. 前端页面

<!DOCTYPE html>
<html lang="ch" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>FileUpload Test</title>
</head>
<body>

    <h3>文件上传</h3>
    <form action="" th:action="@{/file/upload}" enctype="multipart/form-data" method="post">
        <input type="file" name="file"><br> 
        <input type="submit" value="上传">
    </form>

</body>
</html>

文件下载

1. 前端页面

<h3>文件下载</h3>
    <a href="" th:href="@{/file/download/01.jpg}">01.jpg</a>
    <a href="" th:href="@{/file/download/02.png}">02.png</a>

2. 编写控制器

package com.juyss.controller;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * @author ShmeBluk
 * @version 1.0
 * @ClassName: FileController
 * @Desc: 文件上传和下载
 * @package com.juyss.controller
 * @project atguigu-Advanced
 * @date 2020/12/8 19:37
 */
@RestController
@RequestMapping("/file")
public class FileController {

    /**
     * 文件下载控制器
     * @param fileName 要下载的文件名
     * @param request 请求
     * @param response 响应
     * @return 返回响应信息
     */
    @RequestMapping("/download/{fileName}")
    public String download(@PathVariable("fileName") String fileName, HttpServletRequest request, HttpServletResponse response){

        //获取下载文件路径
        //String realPath = request.getServletContext().getRealPath("/download"); //相对路径
        String realPath = "D:\WorkSpace\Demo-Project\atguigu-Advanced\fileupload\src\main\resources\download"; //绝对路径

        //创建文件抽象类
        File file = new File(realPath,fileName);

        //判断文件是否存在
        if(!file.exists()){
            return "文件不存在";
        }

        //从服务器通过文件输入流读入文件,然后通过文件输出流由Response写出给浏览器
        FileInputStream is = null;
        ServletOutputStream os = null;
        try {
            is = new FileInputStream(file);

            //设置响应头信息
            response.setHeader("content-disposition", "attachment:fileName="+ URLEncoder.encode(fileName, "UTF-8"));
            os = response.getOutputStream();

            //IO工具类复制操作
            IOUtils.copy(is, os);

        } catch (IOException e) {
            e.printStackTrace();
            return "文件下载错误";
        } finally {
            //关闭资源
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }
        return "下载成功!!!";
    }

}

原文地址:https://www.cnblogs.com/juyss/p/13332306.html