压缩文件上传

首先压缩文件的上传需要几个maven包,分别用于zip和rar的解压:

<!--zip4j依赖,解压zip压缩-->
        <dependency>
            <groupId>net.lingala.zip4j</groupId>
            <artifactId>zip4j</artifactId>
            <version>1.3.2</version>
        </dependency>

        <!--解压rar压缩-->
        <dependency>
            <groupId>com.github.junrar</groupId>
            <artifactId>junrar</artifactId>
            <version>0.7</version>
        </dependency>

文件上传路径配置,application.yml:
这里用的是本地的c:/upload文件夹目录

updown:
#  dir: /usr/local/nginx/html/081/upload/
#  dir: D:\155\046\upload
  dir: c:/upload/

接下来是controller类:

	@Value("${updown.dir}")
	private String dir;
	
	/**
     * 暂时压缩文件上传用该方法
     * @param file
     * @param year 文件目录以此参数为区分,一年一个文件夹,也可以用UUID,这里有特殊需求采用年份为文件夹
     * @return
     */
	@ApiOperation(value = "上传zip佐证",notes = "上传zip佐证")
	@RequestMapping(value="/zip/upload", method = RequestMethod.POST)
	@ResponseBody
	public ApiResultExten zipUpload(MultipartFile file, String year) {
		return zipRarFileUploadService.handlerUpload2(file, year, dir);
	}

接下来是服务层,代码没有优化,勿喷:

/**
     * 上传zip压缩包,并解压里面文件上传到该压缩包目录下
     * @param zipFile
     * @param year
     * @param dir
     * @return
     */
    public ApiResultExten handlerUpload2(MultipartFile zipFile, String year, String dir) {
        if(zipFile != null) {
            try{
                String zipFileName = zipFile.getOriginalFilename();
                File file = new File(dir + "/" + year + "/" + zipFileName);
                if(!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                // 上传文件
                zipFile.transferTo(file);

                // 根据上传文件解压
                if(!StringUtils.isBlank(zipFileName)) {
                    // zip解压
                    if (zipFileName.toLowerCase().endsWith(".zip")) {
                        ZipFile zFile = new ZipFile(file);
                        zFile.setFileNameCharset("UTF-8");
                        File destDir = new File(dir+year);
                        zFile.extractAll(dir+year);

                        // 获取包内文件信息
                        List<FileHeader> headerList = zFile.getFileHeaders();
                        Date date = new Date();
                        for (FileHeader fileHeader : headerList) {
                            String fileName = fileHeader.getFileName();
                            // 文件路径保存到数据库,非文件夹文件
                            if(!fileHeader.isDirectory()) {
                                MonitorFile monitorFile = new MonitorFile();
                                monitorFile.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                                monitorFile.setCreatedTime(date);
                                monitorFile.setFileYear(year);

                                monitorFile.setFilePath(dir + year + "/" + fileName);
                                if(!StringUtils.isBlank(fileName)) {
                                    if(fileName.contains("/")) {
                                        int i = fileName.lastIndexOf("/");
                                        String substring = fileName.substring(i+1);
                                        monitorFile.setFileName(substring);
                                    }
                                    if(fileName.contains("\\")) {
                                        int i = fileName.lastIndexOf("\\");
                                        String substring = fileName.substring(i+1);
                                        monitorFile.setFileName(substring);
                                    }
                                }
                                planMapper.insertOne(monitorFile);
                            }
                        }
                    } else if(zipFileName.toLowerCase().endsWith(".rar")) {
                        // rar解压
                        unRarFile(dir + year + "/" + zipFileName, dir, year);
                    } else {
                        return ApiResultExten.fail("不支持.zip或.rar之外的文件");
                    }
                }

                return ApiResultExten.success("success");
            } catch (Exception e) {
                log.error(e.getMessage());
                return ApiResultExten.exeception(e);
            }
        } else {
            return ApiResultExten.exeception("文件不能为空");
        }

    }
    
	/**
     * 根据原始rar路径,解压到指定文件夹下.
     *
     * @param srcRarPath 原始rar路径
     * @param dstDirectoryPath 解压到的文件夹
     */
    private synchronized void unRarFile(String srcRarPath, String dstDirectoryPath, String year) {
        if (!srcRarPath.toLowerCase().endsWith(".rar")) {
            System.out.println("非rar文件!");
            return;
        }
        File dstDiretory = new File(dstDirectoryPath);
        if (!dstDiretory.exists()) {// 目标目录不存在时,创建该文件夹
            dstDiretory.mkdirs();
        }
        Archive a = null;
        try {
            a = new Archive(new File(srcRarPath));
            if (a != null) {
                // a.getMainHeader().print(); // 打印文件信息.
                com.github.junrar.rarfile.FileHeader fh = a.nextFileHeader();
                Date date = new Date();
                while (fh != null) {
                    // 防止文件名中文乱码问题的处理
                    String fileName = fh.getFileNameW().isEmpty() ? fh.getFileNameString() : fh.getFileNameW();
                    if (fh.isDirectory()) {
                        File fol = new File(dstDirectoryPath + year + "/" + fileName);
                        fol.mkdirs();
                    } else { // 文件
                        File out = new File(dstDirectoryPath + year + "/" + fileName.trim());
                        try {
                            if (!out.exists()) {
                                if (!out.getParentFile().exists()) {// 相对路径可能多级,可能需要创建父目录.
                                    out.getParentFile().mkdirs();
                                }
                                out.createNewFile();
                            }
                            FileOutputStream os = new FileOutputStream(out);
                            a.extractFile(fh, os);
                            os.close();
                            MonitorFile monitorFile = new MonitorFile();
                            monitorFile.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                            monitorFile.setCreatedTime(date);
                            monitorFile.setFileYear(year);
                            if(!StringUtils.isBlank(fileName)) {
                                if(fileName.contains("\\")) {
                                    int i = fileName.lastIndexOf("\\");
                                    String substring = fileName.substring(i+1);
                                    monitorFile.setFileName(substring);
                                }
                                if(fileName.contains("/")) {
                                    int i = fileName.lastIndexOf("/");
                                    String substring = fileName.substring(i+1);
                                    monitorFile.setFileName(substring);
                                }
                            }
                            monitorFile.setFilePath(dstDirectoryPath + year + "/" + fileName.trim());
                            planMapper.insertOne(monitorFile);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                    fh = a.nextFileHeader();
                }
                a.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

解压rar文件可能会出现问题,原因是rar压缩版本过高,压缩文件不得高于版本4,小于等于版本4的可以解压,高于的没有开源jar包压缩文件不得高于版本4,小于等于版本4的可以解压,高于的没有开源jar包
建议还是通过zip压缩,然后上传,以下是上传后的效果,文件上传到C盘upload目录下,文件路径保存的具体的表中
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Hutool的ZipUtil类来压缩文件,然后使用Java中的HttpURLConnection来上传文件。 以下是一个示例代码: ```java import cn.hutool.core.util.ZipUtil; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class UploadZipFile { public static void main(String[] args) { String zipFileName = "example.zip"; String uploadUrl = "http://example.com/upload"; // 压缩文件 ZipUtil.zip("example", zipFileName); // 上传文件 try { File zipFile = new File(zipFileName); FileInputStream fileInputStream = new FileInputStream(zipFile); URL url = new URL(uploadUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Content-Type", "application/zip"); httpURLConnection.setRequestProperty("Content-Length", String.valueOf(zipFile.length())); OutputStream outputStream = httpURLConnection.getOutputStream(); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } int responseCode = httpURLConnection.getResponseCode(); System.out.println("Response code: " + responseCode); fileInputStream.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上面的示例中,我们首先使用ZipUtil将文件夹example压缩成一个zip文件,然后使用HttpURLConnection向指定的URL上传zip文件。在上传文件时,我们设置了请求方法为POST,Content-Type为application/zip,Content-Length为zip文件的长度。 请注意,这只是一个简单的示例,并且需要根据你的具体情况进行修改。例如,你可能需要添加身份验证或处理服务器响应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值