文件上传下载笔记

这篇博客详细介绍了如何在Java Web应用中实现文件的下载和上传功能。包括使用HttpServlet处理文件下载,通过ServletContext读取文件内容,设置响应头以触发浏览器下载,以及处理多文件下载和上传。同时,还涉及到文件名的编码处理和文件的临时存储及删除操作。
摘要由CSDN通过智能技术生成
package com.example.demo.ctrl;

import org.apache.tomcat.util.http.fileupload.IOUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @Author: CaribbeanSeal
 * @Date: 2020/10/23 0023 1:36
 */
public class DownloadServlet extends HttpServlet {
    /**
     *  客户端  发送请求,告诉浏览器要下载什么文件
     *
     *  服务器  1,获取要下载的文件名
     *          2,读取要下载的文件的内容
     *          3,吧下载的文件内容回传给客户端
     *          4,在回传钱,通过响应头告诉客户端返回的数据类型
     *          5,告诉客户端,收到的数据是用于下载使用(还是使用响应头)
     */

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 获取要下载的文件名
        String downloadFileName = "2.jpg";

        //2 读取要下载的文件内容(通过ServletContext对象可以读取)
        ServletContext servletContext = getServletContext();

        //获取要下载的文件的类型
        String mimeType = servletContext.getMimeType("/file/" + downloadFileName);
        System.out.println("下载的文件的类型:" + mimeType);

        //4 在回传钱,通过响应头告诉客户端返回的数据类型
        resp.setContentType(mimeType);

        //5 告诉客户端收到的数据是用于下载使用(使用响应头)
        //Content-Disposition 响应头,表示收到的数据怎么处理
        //attachment 表示附件,表示下载使用
        //filename 表示指定下载的文件名
        resp.setHeader("Content-Disposition","attachment; filename=" + downloadFileName);

        /*
        斜杠被服务器解析表示地址为http://ip:port/工程名/ 映射到 代码的web目录
         */
        InputStream resourceAsStream = servletContext.getResourceAsStream("/file/" + downloadFileName);

        //commons-io-1.4
        /*
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        */

        //获取响应的输出流
        OutputStream outputStream = resp.getOutputStream();

        //3 把下载的内容回传给客户端
        //读取输入流中全部的数据,复制给输出流,输出给客户端
        IOUtils.copy(resourceAsStream,outputStream);
    }
}
package com.example.demo.ctrl;

import com.example.demo.ZipUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * file-upload
 * 201919 10:41
 *
 * @author
 * @description 单文件和多文件下载
 **/
@RestController
@Slf4j
public class FileDownCtrl {
    @GetMapping(value = "/downSingleFile")
    public String download(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        String filePathName = fileName;
        File file = new File("upload/" + filePathName);
        if (!file.exists()) {
            return "文件不存在";
        }
        //使用URLEncoder解决中文变__问题
        //response.setHeader("Content-Disposition", "attachment;fileName=" + filePathName);
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filePathName, "utf-8"));
        try {
            InputStream inStream = new FileInputStream(file);
            OutputStream os = response.getOutputStream();
            byte[] buff = new byte[1024];
            int i = 0;
            //read方法返回读取到字节数,=0说明到达文件结尾,=-1说明发生错误
            while ((i = inStream.read(buff)) != -1) {
                //write()方法3个参数,可自定义读取字节数0-i;
                os.write(buff, 0, i);
            }
            os.flush();
            os.close();
            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "下载成功";
    }

    @GetMapping("/downMultipleFiles")
    public String multipleFiles(HttpServletResponse response, String[] fileName) throws IOException {
        //1.创建临时文件夹
        String downPath = System.getProperty("user.dir") + "/downzip/";
        File f = new File(downPath);
        //如果不存在该路径就创建
        if (!f.exists()) {
            f.mkdir();
        }
        //2.将需要下载文件复制到临时文件夹
//        List<File> fileList = new ArrayList<>();
        for (int i = 0; i < fileName.length; i++) {
            String uploadPath = System.getProperty("user.dir") + "/upload/" + fileName[i];
//            File file = new File(uploadPath);
//            fileList.add(file);
            ZipUtils.copyFile(uploadPath, downPath + "/" + fileName[i]);
        }
        //3.设置response,设置压缩包名称
        response.setContentType("application/zip");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());
        String filename = format + "down.zip";
        response.setHeader("Content-Disposition", "attachment; filename=" + filename);
        //4.调用工具类,下载zip
        ZipUtils.toZip(downPath, response.getOutputStream(), true);
//        ZipUtils.toZip(fileList,response.getOutputStream());
        //5.删除临时文件夹
        File[] listFiles = f.listFiles();
        for (int i = 0; i < listFiles.length; i++) {
            listFiles[i].delete();
            log.info("正在删除第" + i + "个文件");
        }
        f.delete();
        return "多文件下载成功";
    }
}

package com.example.demo.ctrl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * file-upload
 * 201919 10:41
 *
 * @author
 * @description 单文件和多文件的上传
 **/
@RestController
@Slf4j
public class FileUploadCtrl {

    @PostMapping("/singleFile")
    public String singleFile(@RequestParam("file") MultipartFile file) {
        //判断非空
        if (file.isEmpty()) {
            return "上传的文件不能为空";
        }
        try {
            // 测试MultipartFile接口的各个方法
            log.info("[文件类型ContentType] - [{}]", file.getContentType());
            log.info("[文件组件名称Name] - [{}]", file.getName());
            log.info("[文件原名称OriginalFileName] - [{}]", file.getOriginalFilename());
            log.info("[文件大小] - [{}]", file.getSize());
            //文件路径
            String path = System.getProperty("user.dir") + "/upload/";
            log.info(this.getClass().getName() + "图片路径:" + path);
            File f = new File(path);
            //如果不存在该路径就创建
            if (!f.exists()) {
                f.mkdir();
            }
            File dir = new File(path + file.getOriginalFilename());
            // 文件写入
            file.transferTo(dir);
            return "上传单个文件成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "上传单个文件失败";
        }
    }

    @PostMapping("/multipleFiles")
    public String multipleFiles(@RequestParam("file") MultipartFile[] files) {
        if (null == files && files.length == 0) {
            return null;
        }
        String filePath = System.getProperty("user.dir") + "/upload/";
        log.info(this.getClass().getName() + "图片路径:" + filePath);
        File f = new File(filePath);
        //如果不存在该路径就创建
        if (!f.exists()) {
            f.mkdir();
        }
        for (MultipartFile mf : files) {
            //文件名称
            String filename = mf.getOriginalFilename();
            if (mf.isEmpty()) {
                return "文件名称:" + filename + "上传失败,原因是文件为空!";
            }
            File dir = new File(filePath + filename);
            try {
                //写入文件
                mf.transferTo(dir);
                log.info("文件名称:" + filename + "上传成功");
            } catch (IOException e) {
                log.error(e.toString(), e);
                return "文件名称:" + filename + "上传失败";
            }
        }
        return "多文件上传成功";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值