springMvc上传下载文件工具类

DownLoadFile

public class DownLoadFile {

    /**
    * @Description 判断文件是否存在
    * @param path
    * @Return boolean
    **/
    public static boolean existsFile(String path) {
        File file = new File(path);
        return file.exists() && file.isFile();
    }

    /**
     * @Description 项目相关文件下载工具方法
     * @param response
     * @param request
     * @param filePath 文件完整路径
     * @param fileName 文件名称
     * @param charset 编码
     * @Return void
     **/
    public static void DownLoadFile(HttpServletResponse response, HttpServletRequest request, String filePath, String fileName, String charset) {
        try {
            // 设置编码
            response.setCharacterEncoding(charset);
            InputStream input = null;
            File file = new File(filePath);
            input = FileUtils.openInputStream(file);
            byte[] data = IOUtils.toByteArray(input);
            String userAgent = request.getHeader("User-Agent");
            // IE内核浏览器
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else {
                // 非IE浏览器的处理:
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            }
            response.reset();
            response.setHeader("content-disposition", "attachment;fileName=" + fileName);
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("image/png; charset=UTF-8");
            IOUtils.write(data, response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description 生成压缩文件地址并调用生成压缩文件方法将需要下载的文件写入该地址的压缩包中
     * @param path
     * @param suffix 生成的压缩包文件后缀
     * @Return java.lang.String
     **/
    public static String generateZipFilePath(File path, String suffix) throws Exception {
        String zipFilePath = ""; // 生成的zip文件所在地址
        if(path.isDirectory()){
            zipFilePath = path.getParent().endsWith("/") == false ? path.getParent() + File.separator + path.getName() + "." + suffix: path.getParent() + path.getName() + "." + suffix;
        }else {
            zipFilePath = path.getParent().endsWith("/") == false ? path.getParent() + File.separator : path.getParent();
            zipFilePath += path.getName().substring(0,path.getName().lastIndexOf(".")) + "." + suffix;
        }
        // 输出流
        FileOutputStream outputStream = new FileOutputStream(zipFilePath);
        // 压缩输出流
        ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream));
        generateZipFile(zipOutputStream, path,"");
        zipOutputStream.flush();
        zipOutputStream.close();
        return zipFilePath;
    }

    /**
     * @Description 循环将文件写入压缩包
     * @param zipOutputStream
     * @param file
     * @param childPath
     * @Return void
     **/
    private static void generateZipFile(ZipOutputStream zipOutputStream, File file, String childPath){
        FileInputStream input = null;
        try {
            // 文件为目录
            if (file.isDirectory()) {
                // 得到当前目录里面的文件列表
                File list[] = file.listFiles();
                childPath = childPath + (childPath.length() == 0 ? "" : "/") + file.getName();
                // 循环递归压缩每个文件
                for (File f : list) {
                    generateZipFile(zipOutputStream, f, childPath);
                }
            } else {
                // 压缩文件
                childPath = (childPath.length() == 0 ? "" : childPath + "/") + file.getName();
                zipOutputStream.putNextEntry(new ZipEntry(childPath));
                input = new FileInputStream(file);
                int readLen = 0;
                byte[] buffer = new byte[1024 * 8];
                while ((readLen = input.read(buffer, 0, 1024 * 8)) != -1) {
                    zipOutputStream.write(buffer, 0, readLen);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            // 关闭流
            if (input != null) {
                try {
                    input.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}

FileUploadUtils 

public class FileUploadUtils {
    /**
     *
     * @param file
     * @param path 文件存储相对路径
     * @return
     */
    public static ContributeFile tranferFile(CommonsMultipartFile file, String path){

        ContributeFile powerGenerationFile = new ContributeFile();
        if(file != null) {
            String originalFileName = file.getOriginalFilename();
            //
            powerGenerationFile.setUploadName(originalFileName);
            if (!"".equals(originalFileName)){
                int i = originalFileName.lastIndexOf('.');
                String  name = originalFileName.substring(0, i);

                //得到存储到本地的文件名
                String localFileName = UUID.randomUUID().toString() + "_" + name + getFileSuffix(originalFileName);
                powerGenerationFile.setFileName(localFileName);
                //新建本地文件
                File localFile = new File(path, localFileName);
                powerGenerationFile.setFilePath(path+"\\"+localFileName);
                //创建目录
                File fileDir = new File(path);
                if (!fileDir.isDirectory()) {
                    // 如果目录不存在,则创建目录
                    fileDir.mkdirs();
                }
                //写文件到本地
                try {
                    file.transferTo(localFile);
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

        }

        return powerGenerationFile;
    }
    /**
     * 获取文件后缀
     * @param originalFileName
     * @return
     */
    public static String getFileSuffix(String originalFileName){
        int dot=originalFileName.lastIndexOf('.');
        if((dot>-1)&&(dot<originalFileName.length())){
            return originalFileName.substring(dot);
        }
        return originalFileName;
    }

    /**
     * 删除单个文件
     * @param path 被删除文件的文件名
     * @return 单个文件删除成功返回true,否则返回false
     */
    public static boolean deleteFile(String path) {
        File file = new File(path);
        //路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            return true;
        }
        return false;
    }

}

 

 下载实例

@ResponseBody
	@RequestMapping("downLoadFile")
	public AjaxJson downLoadFile(HttpServletResponse response, HttpServletRequest request, String id) {
		AjaxJson j = new AjaxJson();
		ContributeFile file = contributeFileMapper.getFile(id);
		try {
			String filePath = URLDecoder.decode(file.getFilePath(),"UTF-8");
			if (DownLoadFile.existsFile(filePath)) {
				DownLoadFile.DownLoadFile(response, request, filePath, file.getUploadName(), "UTF-8");
			} else {
				j.setSuccess(false);
				j.setMsg("文件下载失败!失败信息:文件不存在");
			}
		} catch (Exception e) {
			e.printStackTrace();
			j.setSuccess(false);
			j.setMsg("文件下载失败!失败信息:"+e.getMessage());
		}
		return j;
	}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值