java基础上传、下载及压缩

1. 上传

    /**
         * 上传文件
         *
         * @param request
         * @param file   原始文件
         * @param newFileName  新文件名
         * @param filePath   下载存放路径
         * @return 返回空则上传文件成功,否则返回错误信息
         */
        public String uploadFile(HttpServletRequest request, MultipartFile file, String newFileName, String filePath) {
            String errorMesage = "";// 错误信息
            File uploadDir = new File(filePath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            try {
                File originalFile = new File(filePath, newFileName);
                file.transferTo(originalFile);
            } catch (IOException e) {
                e.printStackTrace();
                return "上传附件失败!";
            }
            return errorMesage;
        }

2. 下载

    /**
         * 对路径下代码进行压缩并且下载,
         * @param filepath   路径
         * @param fileName   文件名
         * @param request
         * @param response
         * @return
         */
        public static String downloadFile(String filepath,String fileName,HttpServletRequest request,HttpServletResponse response) {

            response.setCharacterEncoding("utf-8");  //指定文件编码格式
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName="+fileName+".zip");
            try {
                String zipFile = filepath +".zip";
                FileOutputStream fos2 = new FileOutputStream(new File(zipFile));
                //压缩
                toZip(filepath ,fos2);
                //下载
                InputStream inputStream = new FileInputStream(new File(zipFile));
                OutputStream os = response.getOutputStream();
                byte[] b = new byte[2048];
                int length;
                while ((length = inputStream.read(b)) > 0) {
                    os.write(b, 0, length);
                }
                os.close();
                inputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "未找到文件";
            } catch (IOException e) {
                e.printStackTrace();
                return "下载文件失败";
            }
            return null;
        }

3. 压缩

    /**
         * 压缩成ZIP
         * @param srcDir 压缩文件夹路径
         * @param out    压缩文件输出流
         * @throws RuntimeException 压缩失败会抛出运行时异常
         */
        public static void toZip(String srcDir, OutputStream out) throws RuntimeException{
            ZipOutputStream zos = null ;
            try {
                zos = new ZipOutputStream(out);
                File sourceFile = new File(srcDir);
                compress(sourceFile,zos,sourceFile.getName());

            } catch (Exception e) {
                throw new RuntimeException("压缩文件异常",e);
            }finally{
                if(zos != null){
                    try {
                        zos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

        /**
         * 递归压缩方法
         * @param sourceFile 源文件
         * @param zos         zip输出流
         * @param name         压缩后的名称
         * @throws Exception
         */
        private static void compress(File sourceFile, ZipOutputStream zos, String name) throws Exception{
            byte[] buf = new byte[2 * 1024];
            if(sourceFile.isFile()){  //是文件
                // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
                zos.putNextEntry(new ZipEntry(name));
                // copy文件到zip输出流中
                int len;
                FileInputStream in = new FileInputStream(sourceFile);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                // Complete the entry
                zos.closeEntry();
                in.close();
            } else {                //是文件夹
                File[] listFiles = sourceFile.listFiles();
                if(listFiles == null || listFiles.length == 0){
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件,不需要文件的copy
                    zos.closeEntry();
                }else {
                    for (File file : listFiles) {
                        // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName());
                    }
                }
            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值