FileUtil

文件上传,下载工具栏

package com.bfr.telinksemifourm.manage.util;

import com.bfr.telinksemifourm.manage.service.ISystemConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by .
 * Copyright (c) 2020, All Rights Reserved.
 * 
 */
@Component
public class FileUtil {

    private Logger log = LoggerFactory.getLogger(FileUtil.class);

    @Autowired
    private ISystemConfigService systemConfigService;

    /**
     * 上传文件
     *
     * @param file       要上传的文件对象
     * @param fileName   文件名,可以为空,为空的话,就生成一串uuid代替文件名
     * @param customPath 自定义存放路径,这个地址是跟在数据库里配置的路径后面的,
     *                   格式类似 avatar/admin 前后没有 / 前面表示头像,后面是用户的昵称,举例,如果将用户头像全都放在一个文件夹里,这里可以直接传个 avatar
     * @return
     */
    public String upload(MultipartFile file, String fileName, String customPath) {
        try {
            if (file == null || file.isEmpty()) return null;

            if (StringUtils.isEmpty(fileName)) fileName = StringUtil.uuid();
            String suffix = "." + file.getContentType().split("/")[1];
            // 如果存放目录不存在,则创建
            File savePath = new File(systemConfigService.selectAllConfig().get("upload_path").toString() + customPath);
            if (!savePath.exists()) savePath.mkdirs();

            // 给上传的路径拼上文件名与后缀
            String localPath = systemConfigService.selectAllConfig().get("upload_path").toString() + customPath + "/" +
                    fileName + suffix;

            // 上传文件
            // 下面 BufferedOutputStream的构造参数是直接在参数里通过 new FileOutputStream() 的方式传入的,所以它没有对象接收
            // 但下面只关闭了 stream 的流,这个FileOutputStream有没有关闭呢?
            // 答案是关了,跟踪 stream.close() 源码就会发现,这货关闭的就是 OutputStream , 也就是传入的这个输出流
            // 另外实现了AutoCloseable这个接口的流当声明流被放在 try(){} 的()里时,流用完了,程序会自动的调用这个流的close()方法
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(localPath)));
            stream.write(file.getBytes());
            stream.close();

            // 上传成功后返回访问路径
            return systemConfigService.selectAllConfig().get("static_url1").toString() + customPath + "/" + fileName +
                    suffix + "?v=" + StringUtil.randomNumber(1);
        } catch (IOException e) {
            log.error(e.getMessage());
            return null;
        }
    }


    /**
     * 上传文件剪裁图片尺寸
     *
     * @param file       要上传的文件对象
     * @param fileName   文件名,可以为空,为空的话,就生成一串uuid代替文件名
     * @param customPath 自定义存放路径,这个地址是跟在数据库里配置的路径后面的,
     *                   格式类似 avatar/admin 前后没有 / 前面表示头像,后面是用户的昵称,举例,如果将用户头像全都放在一个文件夹里,这里可以直接传个 avatar
     * @return
     */
    public String uploadtop(MultipartFile file, String fileName, String customPath) {
        try {
            if (file == null || file.isEmpty()) return null;

            if (StringUtils.isEmpty(fileName)) fileName = StringUtil.uuid();
            String suffix = "." + file.getContentType().split("/")[1];
            // 如果存放目录不存在,则创建
            File savePath = new File(
                    systemConfigService.selectAllConfig()
                            .get("upload_path").toString() + customPath);
            if (!savePath.exists()) savePath.mkdirs();

            // 给上传的路径拼上文件名与后缀
            String localPath = systemConfigService.selectAllConfig().get("upload_path").toString() + customPath + "/" +
                    fileName + suffix;

            // 上传文件
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(localPath)));
            stream.write(file.getBytes());
            stream.close();
            // 上传成功后返回访问路径
            String url = "/static/" + customPath + "/" + fileName +
                    suffix + "?v=" + StringUtil.randomNumber(1);

            return url;
        } catch (IOException e) {
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * 下载文件
     * @author zxk
     * @date 2020/7/6
     *
     * @param fileName
     * @param customPath
     * @param response
     * @return
     * @throws IOException
     */
    public boolean downFile(String fileName, String customPath, HttpServletResponse response) throws IOException {
//        fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");
        //上传的文件都是保存在/WEB-INF/upload目录下的子目录当中
        String fileSaveRootPath = systemConfigService.selectAllConfig().get("upload_path").toString() + customPath + "/";
//        String fileSaveRootPath = "/static/" + customPath + "/";

        //得到要下载的文件
        File file = new File(fileSaveRootPath + fileName);
        System.out.println("-------  filePath:" + fileSaveRootPath + fileName);

        //如果文件不存在
        if(!file.exists()){
//          map.put("notExist", "您要下载的资源已被删除!!");
            System.out.println("-------  !file.exists()  ---------");
            return false;
        }
        //处理文件名
        String realname = fileName.substring(fileName.indexOf("_")+1);
        //设置响应头,控制浏览器下载该文件
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
        //读取要下载的文件,保存到文件输入流
        FileInputStream in = null;
        try {
            in = new FileInputStream(fileSaveRootPath + fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //创建输出流
        OutputStream out = response.getOutputStream();
        //创建缓冲区
        byte buffer[] = new byte[1024];
        int len = 0;
        //循环将输入流中的内容读取到缓冲区当中
        while((len=in.read(buffer))>0){
            //输出缓冲区的内容到浏览器,实现文件下载
            out.write(buffer, 0, len);
        }
        //关闭文件输入流
        in.close();
        //关闭输出流
        out.close();
//        map.put("success", "成功");
        return true;
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值