java--文件上传与压缩下载(使用java 1.8 ZipOutputStream)

1.使用java 1.8 ZipOutputStream 下载压缩文件

    /**
     * 批量文件压缩后下载
     * import org.apache.tools.zip.ZipEntry;
     * import org.apache.tools.zip.ZipOutputStream;
     */
    @RequestMapping("/wmg-ml!fileDownload.do")
    public ResponseEntity<byte[]> fileDownload(HttpServletRequest request) throws IOException {
        ResponseEntity<byte[]> responseEntity = null;

        //1.服务器端输出压缩文件
        //获取登录用户信息
        OpuOmUser currentUser = SecurityContext.getCurrentUser();
        String userLoginName =  currentUser.getUserName();
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmsssss");
        String dateFormat = sdf.format(now);
        String resourcesName ="/[反馈附件]"+dateFormat+"_"+userLoginName+".zip";//服务器段压缩后的文件名 采用:“[反馈附件]-”+当前时间戳+"_"+处理人 的形式
        String zipFileName = STORAGE_URL+feedbackFilePath+resourcesName;//压缩文件的完整路径名
        FileOutputStream fileOut = new FileOutputStream(zipFileName)
        ZipOutputStream zipOut = new ZipOutputStream(fileOut );//生成并输出压缩文件
        InputStream input = null;
        //2.将服务器需要压缩的文件添加到服务器端的压缩文件中
        String csId = request.getParameter("csId");
        String fId = request.getParameter("fId");
        List<Map> sysFileList = getFileUrl(csId,fId);//需要压缩的文件
        if(null != sysFileList && sysFileList.size() >0){
            int listSize = sysFileList.size();
            for(int i = 0; i < listSize; i++){
                String filename = sysFileList.get(i).get("FILE_NAME").toString();
                String filePath = sysFileList.get(i).get("FILE_PATH").toString();
                String name = STORAGE_URL + filePath+"/"+filename;//文件的完整路径名
                input = new FileInputStream(new File(name));//转换为文件流
                zipOut.putNextEntry(new ZipEntry(filename));//将文件添加至压缩包
                // 写入当前条目所对应的具体内容
                byte[] buff = new byte[1024];
                int len = 0;
                while ((len = input.read(buff)) != -1) {
                    zipOut.write(buff, 0, len);
                }
                input.close();//关闭流
            }
            fileOut.close();//关闭流
            zipOut.close();//关闭流
            //3.前端下载 服务器的压缩文件
            File file = new File(zipFileName);//读取压缩文件
            HttpHeaders headers = new HttpHeaders();
            String filename = new String(resourcesName.getBytes("utf-8"),"iso-8859-1");
            headers.setContentDispositionFormData("attachment", filename);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
            //4.删除服务器端的压缩文件
            file.delete();//删除压缩包
        }

        return responseEntity;

    }

2.文件上传

 /**
     * 将附件上传至服务器磁盘的指定路径下
     *
     * @param filePath           附件上传的服务器磁盘路径
     * @param fileName           文件名
     * @param multipartFile         页面上传的附件对象
     * @param isAbsoluteFilePath 是否为绝对路径。true表示为filePath为服务器的绝对路径,false表示为当前应用下的相对路径
     * @param autoBuildDir       true表示当文件路径不存在时自动创建
     * @param canCover           true表示当指定文件已经存在时可覆盖原有文件
     * @return true表示上传成功,false表示上传失败
     */
    @Override
    public boolean uploadFile(String filePath,
                              String fileName,
                              MultipartFile multipartFile,
                              boolean isAbsoluteFilePath,
                              boolean autoBuildDir,
                              boolean canCover) {
        boolean result = false;

        if (multipartFile == null || multipartFile.isEmpty()
                || multipartFile.getSize() == 0 || filePath == null || filePath.trim().length() == 0) {
            return result;
        }

        InputStream in = null;
        OutputStream out = null;

        try {
            // 文件路径格式处理
            filePath = filePath.replace("\\", "/");

            // 上传附件文件夹路径,如果是绝对路径则使用绝对路径,如果不是则使用默认路径
            String directoryPath = isAbsoluteFilePath ? filePath : STORAGE_URL + filePath;

            // 完整上传路径
            String wholeFilePath = directoryPath + "/" + fileName;

            // 如果文件目录不存在则创建
            if (autoBuildDir) {
                File dir = new File(directoryPath);
                if (!dir.exists())
                    dir.mkdirs();
            }

            // 输出附件
            File outputFile = new File(wholeFilePath);

            //如果文件不存在则可上传,如果文件存在并且设置为可覆盖则也可上传
            boolean isFileExist = outputFile.exists();
            if (!isFileExist || (isFileExist && canCover)) {

                boolean canUpload = true; //标识是否能够上传文件

                //如果文件存在要先删除,如果文件不存在则标识为可上传
                if (isFileExist)
                    canUpload = outputFile.delete();

                if (canUpload) {

                    // 保存附件至服务器

                    int available = 0;
                    in = new BufferedInputStream(multipartFile.getInputStream(), BUFFER_SIZE);
                    out = new BufferedOutputStream(new FileOutputStream(outputFile), BUFFER_SIZE);
                    byte[] buffer = new byte[BUFFER_SIZE];
                    while ((available = in.read(buffer)) > 0) {
                        if (available < BUFFER_SIZE)
                            out.write(buffer, 0, available);
                        else
                            out.write(buffer, 0, BUFFER_SIZE);
                    }

                    result = true;//上传附件成功
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,可以使用Java中的ZipOutputStream类实现文件的批量下载并合成一个压缩包。 首先,需要创建一个ZipOutputStream对象,用于将文件写入压缩包中。然后,遍历需要下载文件列表,将每个文件逐个添加到压缩包中。 示例代码如下: ```java import java.io.*; import java.util.zip.*; public class FileDownloader { public static void main(String[] args) { // 定义要下载文件列表 String[] filesToDownload = {"file1.txt", "file2.txt", "file3.txt"}; // 定义压缩包的文件名 String zipFileName = "download.zip"; try { // 创建压缩包输出流 FileOutputStream fos = new FileOutputStream(zipFileName); ZipOutputStream zos = new ZipOutputStream(fos); // 遍历文件列表,逐个添加到压缩包中 for (String fileName : filesToDownload) { // 创建文件输入流 FileInputStream fis = new FileInputStream(fileName); // 添加压缩包条目 zos.putNextEntry(new ZipEntry(fileName)); // 将文件内容写入压缩包 byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) > 0) { zos.write(buffer, 0, len); } // 关闭输入流 fis.close(); // 关闭条目 zos.closeEntry(); } // 关闭压缩包输出流 zos.close(); fos.close(); System.out.println("文件下载成功!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上述示例代码中,我们定义了要下载文件列表,以及压缩包的文件名。然后,创建了一个ZipOutputStream对象,用于将文件写入压缩包中。在遍历文件列表的过程中,我们使用FileInputStream读取文件内容,并使用ZipOutputStream文件内容写入压缩包中。最后,关闭压缩包输出流,完成文件下载压缩包的生成。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值