spring-boot实现文件上传下载

 /**
     * 本地文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file, HttpServletRequest request) throws FileException {
        //删除原来的文件
        FileUtils.deleteFile(file);
        //上传文件
        String uploadfile = FileUtils.uploadfile(file);
        StringBuffer url = request.getRequestURL();
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getSession().getServletContext().getContextPath()).toString();
        return tempContextUrl + "/upgrued/download" + uploadfile;
    }

    @Override
    public void downloadFile(String filePath, HttpServletResponse response) throws UnsupportedEncodingException {
        String path = System.getProperty("user.dir");
        File file = new File(path + filePath);
        String filename = file.getName();
        //获取文件后缀
        //设置响应的信息
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf8"));
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        //设置浏览器接受类型为流
        response.setContentType("application/octet-stream;charset=UTF-8");

        try (
            FileInputStream in = new FileInputStream(file);
        ) {
            // 将文件写入输入流
            OutputStream out = response.getOutputStream();

            //其他类型的文件,按照普通文件传输 如(zip、rar等压缩包)
            int len;
            //一次传输1M大小字节
            byte[] bytes = new byte[1024];
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes, 0, len);
            }
            out.close();
        } catch (IOException ex) {
            logger.info("文件下载异常", ex);
        }
    }
     @Override
    public void downloadRdpFile(TbEquipmentDTO dto, HttpServletResponse response){
        String ipAddress = dto.getIpAddress();
        String remoteLoginUser = dto.getRemoteLoginUser();
        String outRdpFileSrting = "auto connect:i:1\r\n"
            .concat("full address:s:").concat(ipAddress).concat("\r\n")
            .concat("username:s:").concat(remoteLoginUser).concat("\r\n");
        try (
            OutputStream out = response.getOutputStream();
            ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(outRdpFileSrting.getBytes(StandardCharsets.UTF_8));
        ) {
            String filename = "device-".concat(ipAddress).concat(".rdp");
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf8"));
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setContentType("application/octet-stream;charset=UTF-8");
            // 将文件写入输入流
            int len;
            //一次传输1M大小字节
            byte[] bytes = new byte[1024];
            while ((len = tInputStringStream.read(bytes)) != -1) {
                out.write(bytes, 0, len);
            }
        } catch (UnsupportedEncodingException ex) {
            logger.info("类型转换异常", ex);
        } catch (IOException ex) {
            logger.info("文件下载异常", ex);
        }
    }

工具类

package com.yyt.common.core.utils.file;

import cn.hutool.core.io.FileUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.UUID;

/**
 * 文件处理工具类
 *
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class FileUtils extends FileUtil {

    /**
     * 下载文件名重新编码
     *
     * @param response     响应对象
     * @param realFileName 真实文件名
     * @return
     */
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
        String percentEncodedFileName = percentEncode(realFileName);

        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
            .append(percentEncodedFileName)
            .append(";")
            .append("filename*=")
            .append("utf-8''")
            .append(percentEncodedFileName);

        response.addHeader("Access-Control-Allow-Origin" , "*");
        response.addHeader("Access-Control-Expose-Headers" , "Content-Disposition,download-filename");
        response.setHeader("Content-disposition" , contentDispositionValue.toString());
        response.setHeader("download-filename" , percentEncodedFileName);
    }

    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+" , "%20");
    }

    /**
     * 本地文件上传
     * @param file
     * @return
     */
    public static String uploadfile(MultipartFile file) {
        String path = System.getProperty("user.dir") + "/upload/";
        String originalFilename = file.getOriginalFilename();
        int lastIndexOf = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(lastIndexOf);
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdirs();
        }
        String name = file.getOriginalFilename();
        try {
            file.transferTo(new File(realPath +"/"+ name));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "/upload/" + name;
    }

    /**
     * 文件删除
     *
     */
    public static void deleteFile(MultipartFile file){
        String path = System.getProperty("user.dir");
        path = path + file.getOriginalFilename();
        File fileDel = new File(path);
        boolean isOk = fileDel.exists();
        if(isOk){
            fileDel.delete();
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alaia.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值