java上傳rar文件_java實現上傳zip/rar壓縮文件,自動解壓

在pom中添加解壓jar依賴

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.1.2.RELEASE

com.hf

uncompress

0.0.1-SNAPSHOT

uncompress

上傳壓縮文件(rar或者zip格式),解壓

1.8

org.springframework.boot

spring-boot-starter-web

org.projectlombok

lombok

true

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-starter-thymeleaf

net.lingala.zip4j

zip4j

1.3.2

com.github.junrar

junrar

0.7

org.springframework.boot

spring-boot-maven-plugin

解壓zip/rar的工具類

package com.hf.uncompress.utils;

import com.github.junrar.Archive;

import com.github.junrar.rarfile.FileHeader;

import lombok.extern.slf4j.Slf4j;

import net.lingala.zip4j.core.ZipFile;

import java.io.File;

import java.io.FileOutputStream;

/**

* @Description: 解壓rar/zip工具類

* @Date: 2019/1/22

* @Auther:

*/

@Slf4j

public class UnPackeUtil {

/**

* zip文件解壓

*

* @param destPath 解壓文件路徑

* @param zipFile 壓縮文件

* @param password 解壓密碼(如果有)

*/

public static void unPackZip(File zipFile, String password, String destPath) {

try {

ZipFile zip = new ZipFile(zipFile);

/*zip4j默認用GBK編碼去解壓,這里設置編碼為GBK的*/

zip.setFileNameCharset("GBK");

log.info("begin unpack zip file....");

zip.extractAll(destPath);

// 如果解壓需要密碼

if (zip.isEncrypted()) {

zip.setPassword(password);

}

} catch (Exception e) {

log.error("unPack zip file to " + destPath + " fail ....", e.getMessage(), e);

}

}

/**

* rar文件解壓(不支持有密碼的壓縮包)

*

* @param rarFile rar壓縮包

* @param destPath 解壓保存路徑

*/

public static void unPackRar(File rarFile, String destPath) {

try (Archive archive = new Archive(rarFile)) {

if (null != archive) {

FileHeader fileHeader = archive.nextFileHeader();

File file = null;

while (null != fileHeader) {

// 防止文件名中文亂碼問題的處理

String fileName = fileHeader.getFileNameW().isEmpty() ? fileHeader.getFileNameString() : fileHeader.getFileNameW();

if (fileHeader.isDirectory()) {

//是文件夾

file = new File(destPath + File.separator + fileName);

file.mkdirs();

} else {

//不是文件夾

file = new File(destPath + File.separator + fileName.trim());

if (!file.exists()) {

if (!file.getParentFile().exists()) {

// 相對路徑可能多級,可能需要創建父目錄.

file.getParentFile().mkdirs();

}

file.createNewFile();

}

FileOutputStream os = new FileOutputStream(file);

archive.extractFile(fileHeader, os);

os.close();

}

fileHeader = archive.nextFileHeader();

}

}

} catch (Exception e) {

log.error("unpack rar file fail....", e.getMessage(), e);

}

}

}

頁面HTML

Title

上傳壓縮包:

解壓路徑:

解壓密碼(為空可不傳):

controller代碼:

package com.hf.uncompress.controller;

import com.hf.uncompress.Result.AjaxList;

import com.hf.uncompress.service.FileUploadService;

import com.hf.uncompress.vo.PackParam;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

/**

* @Description:

* @Date: 2019/1/22

* @Auther:

*/

@Controller

@RequestMapping("/user")

@Slf4j

public class FileUploadController {

@Autowired

private FileUploadService fileUploadService;

@GetMapping("/redirect")

public String redirectHtml() {

return "work";

}

@PostMapping("/upload/zip")

@ResponseBody

public String uploadZip(MultipartFile zipFile, @RequestBody PackParam packParam) {

AjaxListajaxList = fileUploadService.handlerUpload(zipFile, packParam);

return ajaxList.getData();

}

}

service實現類代碼

package com.hf.uncompress.service.impl;

import com.hf.uncompress.Result.AjaxList;

import com.hf.uncompress.enums.FileTypeEnum;

import com.hf.uncompress.service.FileUploadService;

import com.hf.uncompress.utils.UnPackeUtil;

import com.hf.uncompress.vo.PackParam;

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;

import java.io.IOException;

/**

* @Description:

* @Date: 2019/1/22

* @Auther:

*/

@Service

@Slf4j

public class FileUploadServiceImpl implements FileUploadService {

@Override

public AjaxListhandlerUpload(MultipartFile zipFile, PackParam packParam) {

if (null == zipFile) {

return AjaxList.createFail("請上傳壓縮文件!");

}

boolean isZipPack = true;

String fileContentType = zipFile.getContentType();

//將壓縮包保存在指定路徑

String packFilePath = packParam.getDestPath() + File.separator + zipFile.getName();

if (FileTypeEnum.FILE_TYPE_ZIP.type.equals(fileContentType)) {

//zip解壓縮處理

packFilePath += FileTypeEnum.FILE_TYPE_ZIP.fileStufix;

} else if (FileTypeEnum.FILE_TYPE_RAR.type.equals(fileContentType)) {

//rar解壓縮處理

packFilePath += FileTypeEnum.FILE_TYPE_RAR.fileStufix;

isZipPack = false;

} else {

return AjaxList.createFail("上傳的壓縮包格式不正確,僅支持rar和zip壓縮文件!");

}

File file = new File(packFilePath);

try {

zipFile.transferTo(file);

} catch (IOException e) {

log.error("zip file save to " + packParam.getDestPath() + " error", e.getMessage(), e);

return AjaxList.createFail("保存壓縮文件到:" + packParam.getDestPath() + " 失敗!");

}

if (isZipPack) {

//zip壓縮包

UnPackeUtil.unPackZip(file, packParam.getPassword(), packParam.getDestPath());

} else {

//rar壓縮包

UnPackeUtil.unPackRar(file, packParam.getDestPath());

}

return AjaxList.createSuccess("解壓成功");

}

}

使用到的枚舉類:

package com.hf.uncompress.enums;

import lombok.AllArgsConstructor;

import lombok.NoArgsConstructor;

/**

* @Description: 壓縮文件類型

* @Date: 2019/1/22

* @Auther:

*/

@AllArgsConstructor

@NoArgsConstructor

public enum FileTypeEnum {

FILE_TYPE_ZIP("application/zip", ".zip"),

FILE_TYPE_RAR("application/octet-stream", ".rar");

public String type;

public String fileStufix;

public static String getFileStufix(String type) {

for (FileTypeEnum orderTypeEnum : FileTypeEnum.values()) {

if (orderTypeEnum.type.equals(type)) {

return orderTypeEnum.fileStufix;

}

}

return null;

}

}

同一返回值定義:

package com.hf.uncompress.Result;

import lombok.AllArgsConstructor;

import lombok.Data;

import lombok.NoArgsConstructor;

/**

* @Description: 返回值處理

* @Date: 2019/1/22

* @Auther:

*/

@AllArgsConstructor

@NoArgsConstructor

@Data

public class AjaxList{

private boolean isSuccess;

private T data;

public static AjaxListcreateSuccess(T data) {

return new AjaxList(true, data);

}

public static AjaxListcreateFail(T data) {

return new AjaxList(false, data);

}

}

前端上傳封裝的vo

package com.hf.uncompress.vo;

import lombok.Data;

/**

* @Description: 上傳壓縮的參數

* @Date: 2019/1/23

* @Auther:

*/

@Data

public class PackParam {

/**

* 解壓密碼

*/

private String password;

/**

* 解壓文件存儲地址

*/

private String destPath;

}

在application.properties中定義其上傳的閥域

#設置上傳單個文件的大小限制

spring.servlet.multipart.max-file-size=500MB

# 上傳文件總的最大值

spring.servlet.multipart.max-request-size=500MB

spring.thymeleaf.cache=false

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/452761.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/452761.shtml
英文地址,請注明出處:http://en.pswp.cn/news/452761.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

從MapReduce的執行來看如何優化MaxCompute(原ODPS) SQL

摘要: SQL基礎有這些操作(按照執行順序來排列): from join(left join, right join, inner join, outer join ,semi join) where group by select sum distinct count order by 如果我們能理解mapreduce是怎么實現這些SQL中的基本操…

套接字(socket)基本知識與工作原理

套接字(socket)基本知識與工作原理 一、Socket相關概念 Socket通常也稱作“套接字”,用于描述IP地址和端口,是一個通信鏈的句柄。(其實就是兩個程序通信用的。) SOCKET用于在兩個基于TCP/IP協議的應用程序之…

python 多線程--重點知識

1.全局變量global的用法 2.多線程共享全局變量-args參數 注意args參數類型為元組,逗號不能少!

Flask WTForm表單的使用

運行環境: python2.7 flask 0.11 flask-wtf 0.14.2 wtform能夠通過一個類定義一些字段,這些字段會在前端生成標簽,并且通過設置字段的驗證規則,自動判斷前端輸入數據的格式。 一般用于用戶登錄,用戶注冊等信息錄入。…

Java與C#個人之比較

網上這方面的比較文章已經有不少了,不過大都是要么從很高的角度說的,要么就是從底層說的,本人就以自己這幾年的編程經歷中的感受,來談談自己的體會。 相似性: Java和C#都是一門面向對象的語言,Java更多地…

java利用子類求正方形_Java程序設計實驗2011

(2)掌握對象的聲明和使用;(3)掌握構造方法的概念和使用;(4)掌握類及成員的訪問控制符。2、實驗任務(1)閱讀下面的程序,在main()方法里添加語句完成如下的功能:①創建一個MyV alue類的對象myV alue。②為myV alue對象中的value域賦…

當導用模塊與包的import與from的問題(模塊與包的調用)

當在views.py里寫impor models會不會報錯呢? 1、Python里面的py文件都是每一行的代碼。2、Python解釋器去找一個模塊的時候,只去sys.path的路徑里找3、django項目啟動(django項目的啟動文件是manage.py)啟動項目是將manage.py的路…

ack和seq

ACK (Acknowledgement),即確認字符,在數據通信中,接收站發給發送站的一種傳輸類控制字符。表示發來的數據已確認接收無誤。 seq是序列號,這是為了連接以后傳送數據用的,ack是對收到的數據包的確認&#xff…

MySQL中的information_schema

0.引言 近日在學習網絡安全的sql注入時,用到mysql中的information_schema數據庫,其思路是利用information_schema中的SCHEMA獲取數據庫中的table名稱。現在對相關數據庫進行總結,方便以后復習使用。 2.information_schema數據庫 informati…

linux配置防火墻,開啟端口

linux配置防火墻,開啟端口 Centos7,配置防火墻,開啟端口  1.查看已開放的端口(默認不開放任何端口)    firewall-cmd --list-ports  2.開啟80端口    firewall-cmd --zonepublic(作用域) --add-port80/tcp(端口和訪問類型) --permanent(永久…

使用Intel編譯器系列合集

好的帖子:http://topic.csdn.net/u/20080327/16/071b45df-3795-4bf1-9c4d-da4eb5aaa739.html參考手冊:http://software.intel.com/sites/products/documentation/studio/composer/en-us/2011Update/compiler_c/index.htm 說明:本系列文章為個…

【前端】這可能是你看過最全的css居中解決方案了~

1.水平居中&#xff1a;行內元素解決方案 適用元素&#xff1a;文字&#xff0c;鏈接&#xff0c;及其其它inline或者inline-*類型元素&#xff08;inline-block&#xff0c;inline-table&#xff0c;inline-flex&#xff09; html部分代碼:<div>文字元素</div><…

java手機一款三國游戲_JAVA熱游—富甲三國之雄霸天下原創心得

因為工作忙碌的關系&#xff0c;很長時間都沒有來關注手機游戲論壇&#xff0c;這款富甲三國.雄霸天下&#xff0c;我也是前天才拿到手。游戲比想象中的簡單&#xff0c;個人僅用了兩個小時時間&#xff0c;就將三個人物全部通關。游戲的開始畫面制作得比較精美&#xff0c;而且…

Python多線程--互斥鎖、死鎖

1、互斥鎖 為解決資源搶奪問題&#xff0c;使用mutex Threading.Lock()創建鎖&#xff0c;使用mutex.acquire()鎖定&#xff0c;使用mutex.release()釋放鎖。 代碼一&#xff1a; import threading import time# 定義一個全局變量 g_num 0def test1(num):global g_num# 上鎖…

freemind 要下載java_Freemind

動手編輯先按Ctrln&#xff0c;新建一個文件。這時出現了一個根節點。用光標單擊它&#xff0c;改成“我學FreeMind”&#xff0c;然后在節點之外任一地方點擊鼠標(或按Enter)完成編輯。然后&#xff0c;按Insert鍵&#xff0c;輸入“下載安裝”&#xff0c;按Enter鍵&#xff…

本地連不上遠程mysql數據庫(2)

Host is not allowed to connect to this MySQL server解決方法 今天在ubuntu上面裝完MySQL&#xff0c;卻發現在本地登錄可以&#xff0c;但是遠程登錄卻報錯Host is not allowed to connect to this MySQL server,找了半天試了網上的一些方法都沒有解決&#xff0c;最終在一篇…

理解EnterCriticalSection 臨界區

通俗解釋就像上廁所&#xff1a; 門鎖了&#xff0c;就等著&#xff0c;等到別人出來了&#xff0c;進去鎖上&#xff0c;然后該干什么干什么&#xff0c;干完了&#xff0c;把門打開 門沒鎖&#xff0c;就進去&#xff0c;鎖上&#xff0c;然后該干什么干什么&#xff0c;干…

Python多線程--UDP聊天器

import socket import threadingdef recv_msg(udp_socket):"""接收數據并顯示"""# 接收數據while True:recv_data udp_socket.recvfrom(1024)print(recv_data)def send_msg(udp_socket, dest_ip, dest_port):"""發送數據"&…

mvc:default-servlet-handler/作用

<mvc:default-servlet-handler/>使用默認的servlet來相應靜態文件&#xff0c;因為在web.xml中使用了DispatcherServlet截獲所有的請求url&#xff0c;而引入<scprit type"text/javascript" src"js/jquery-1.11.0.mim.js"/>的時候&#xff0c;…