spring boot 上传与下载

package org.dvt.utils;

import com.baomidou.mybatisplus.extension.api.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.dvt.base.Result;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * (TdSystemLaws)表控制层
 *
 * @author makejava
 * @since 2020-08-03 10:15:53
 */
@RestController
@RequestMapping("uploadAndDownload")
public class UploadAndDownload {

    /*下载文件*/
    /**
     * 平台实现更新包下载
     *
     * @param request
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/download")
    @RequiresPermissions("update:manage:download")
    public R downloadFile(HttpServletRequest request,
                          HttpServletResponse response, String fileFullName) throws UnsupportedEncodingException {
//        String rootPath = propertiesconfig.getUploadpacketPath();//这里是我在配置文件里面配置的根路径,各位可以更换成自己的路径之后再使用(例如:D:/test)
//        String FullPath = rootPath + fileFullName;//将文件的统一储存路径和文件名拼接得到文件全路径
        File packetFile = new File(fileFullName);
        String fileName = packetFile.getName(); //下载的文件名
        File file = new File(fileFullName);
        // 如果文件名存在,则进行下载
        if (file.exists()) {
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("Download the successfully!");
            } catch (Exception e) {
                System.out.println("Download the failed!");
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {//对应文件不存在
            try {
                //设置响应的数据类型是html文本,并且告知浏览器,使用UTF-8 来编码。
                response.setContentType("text/html;charset=UTF-8");

                //String这个类里面, getBytes()方法使用的码表,是UTF-8,  跟tomcat的默认码表没关系。 tomcat iso-8859-1
                String csn = Charset.defaultCharset().name();

                System.out.println("默认的String里面的getBytes方法使用的码表是: " + csn);

                //1. 指定浏览器看这份数据使用的码表
                response.setHeader("Content-Type", "text/html;charset=UTF-8");
                OutputStream os = response.getOutputStream();

                os.write("对应文件不存在".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /*上传文件*/
    @PostMapping("/upload")
    public Result upload (@RequestParam("file") MultipartFile file,String moduleName){
        Map<String,String> map = new HashMap<>();
        String pathFileName="";
        String fileName="";
        //判断文件是否为空
        if(file.isEmpty()){
            return Result.fail("上传文件为空!");
        }
        //创建输入输出流
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            /*年月*/
            SimpleDateFormat formatY = new SimpleDateFormat("yyyyMM");
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
            Date date = new Date();
            String YYYYMM = formatY.format(date);
            String YYYYMMDD = format.format(date);
            //指定上传的位置为
            /*先建立上级(一起创建就报错)*/
//            String pathHead = "D:/HeNanAudit/FileUpload/"+moduleName+"/";
            String pathHead = "/home/hnsj/hnauditapi/HeNanAudit/"+moduleName+"/";
            File pathHeads = new File(pathHead);
            //判断文件父目录是否存在
            if(!pathHeads.getParentFile().exists()){
                //不存在就创建一个
                pathHeads.getParentFile().mkdir();
            }
            /*再次创建文件夹路径*/
            String path = pathHead + YYYYMM+"/";
            File pathTwoHeads = new File(path);
            //判断文件父目录是否存在
            if(!pathTwoHeads.getParentFile().exists()){
                //不存在就创建一个
                pathTwoHeads.getParentFile().mkdir();
            }
            //获取文件的输入流
            inputStream = file.getInputStream();
            //获取上传时的文件名
            fileName = file.getOriginalFilename();
            String splitStr = null;
            int j = fileName.indexOf("."); // 找分隔符的位置
            splitStr = fileName.substring(0, j);// 找到分隔符,截取子字符串
            String suffixName = fileName.substring(fileName.lastIndexOf("."));//后缀名
            fileName = splitStr + YYYYMMDD + suffixName;
            //注意是路径+文件名
            pathFileName = path + fileName;
            File targetFile = new File(pathFileName);
            //判断文件父目录是否存在
            if(!targetFile.getParentFile().exists()){
                //不存在就创建一个
                targetFile.getParentFile().mkdir();
            }
            //获取文件的输出流
            outputStream = new FileOutputStream(targetFile);
            //最后使用资源访问器FileCopyUtils的copy方法拷贝文件
            FileCopyUtils.copy(inputStream, outputStream);
            map.put("fileName",fileName);
            map.put("pathFileName",pathFileName);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //无论成功与否,都有关闭输入输出流
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok(map);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值