SpringBoot+fileUpload獲取文件上傳進(jìn)度
我本人在網(wǎng)上找了很多關(guān)于文件上傳進(jìn)度獲取的文章,普遍基于spring MVC 框架通過 fileUpload 實(shí)現(xiàn),對(duì)于spring Boot 通過 fileUpload 實(shí)現(xiàn)的帖子非常少,由于小弟學(xué)藝不精,雖然 Spring Boot 和 Spring MVC 相差不大,只是配置方式的差別,還是搞了很久,上傳此文章的目的是希望自己作為文本保留,以便日后查看備忘,并且希望通過我的例子可以幫助到其他人而已,如果各位大佬發(fā)現(xiàn)小弟對(duì)于某些知識(shí)有誤解,還請(qǐng)不吝賜教,先謝謝各位前輩了!
寫此篇文章之前我查了很多關(guān)于spring MVC 框架通過 fileUpload 實(shí)現(xiàn)進(jìn)度條的帖子和文章,在此對(duì)各位作者表示感謝!
本功能基于commons fileUpload 組件實(shí)現(xiàn)
1.首先,不能在程序中直接使用 fileUpload.parseRequest(request)的方式來獲取 request 請(qǐng)求中的 multipartFile 文件對(duì)象,原因是因?yàn)樵?spring 默認(rèn)的文件上傳處理器 multipartResolver 指向的類CommonsMultipartResolver 中就是通過 commons fileUpload 組件實(shí)現(xiàn)的文件獲取,因此,在代碼中再次使用該方法,是獲取不到文件對(duì)象的,因?yàn)榇藭r(shí)的 request 對(duì)象是不包含文件的,它已經(jīng)被CommonsMultipartResolver 類解析處理并轉(zhuǎn)型。
CommonsMultipartResolver 類中相關(guān)源碼片段:
protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
String encoding = determineEncoding(request);
FileUpload fileUpload = prepareFileUpload(encoding);
try {
List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
return parseFileItems(fileItems, encoding);
}
catch (FileUploadBase.SizeLimitExceededException ex) {
throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
}
catch (FileUploadBase.FileSizeLimitExceededException ex) {
throw new MaxUploadSizeExceededException(fileUpload.getFileSizeMax(), ex);
}
catch (FileUploadException ex) {
throw new MultipartException("Failed to parse multipart servlet request", ex);
}
}
2.由于spring 中的 CommonsMultipartResolver 類中并沒有加入 processListener 文件上傳進(jìn)度監(jiān)聽器,所以,直接使用 CommonsMultipartResolver 類是無法監(jiān)聽文件上傳進(jìn)度的,如果我們需要獲取文件上傳進(jìn)度,就需要繼承 CommonsMultipartResolver 類并重寫 parseRequest 方法,在此之前,我們需要?jiǎng)?chuàng)建一個(gè)實(shí)現(xiàn)了 processListener 接口的實(shí)現(xiàn)類用于監(jiān)聽文件上傳進(jìn)度。
processListener接口實(shí)現(xiàn)類:
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.ProgressListener;
import org.springframework.stereotype.Component;
@Component
public class UploadProgressListener implements ProgressListener{
private HttpSession session;
public void setSession(HttpSession session){
this.session=session;
ProgressEntity status = new ProgressEntity();
session.setAttribute("status", status);
}
/*
* pBytesRead 到目前為止讀取文件的比特?cái)?shù) pContentLength 文件總大小 pItems 目前正在讀取第幾個(gè)文件
*/
@Override
public void update(long pBytesRead, long pContentLength, int pItems) {
ProgressEntity status = (ProgressEntity) session.getAttribute("status");
status.setpBytesRead(pBytesRead);
status.setpContentLength(pContentLength);
status.setpItems(pItems);
}
}
ProgressEntity 實(shí)體類:
import org.springframework.stereotype.Component;
@Component
public class ProgressEntity {
private long pBytesRead = 0L; //到目前為止讀取文件的比特?cái)?shù)
private long pContentLength = 0L; //文件總大小
private int pItems; //目前正在讀取第幾個(gè)文件
public long getpBytesRead() {
return pBytesRead;
}
public void setpBytesRead(long pBytesRead) {
this.pBytesRead = pBytesRead;
}
public long getpContentLength() {
return pContentLength;
}
public void setpContentLength(long pContentLength) {
this.pContentLength = pContentLength;
}
public int getpItems() {
return pItems;
}
public void setpItems(int pItems) {
this.pItems = pItems;
}
@Override
public String toString() {
float tmp = (float)pBytesRead;
float result = tmp/pContentLength*100;
return "ProgressEntity [pBytesRead=" + pBytesRead + ", pContentLength="
+ pContentLength + ", percentage=" + result + "% , pItems=" + pItems + "]";
}
}
最后,是繼承 CommonsMultipartResolver 類的自定義文件上傳處理類:
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
public class CustomMultipartResolver extends CommonsMultipartResolver{
@Autowired
private UploadProgressListener uploadProgressListener;
@Override
protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
String encoding = determineEncoding(request);
FileUpload fileUpload = prepareFileUpload(encoding);
uploadProgressListener.setSession(request.getSession());//問文件上傳進(jìn)度監(jiān)聽器設(shè)置session用于存儲(chǔ)上傳進(jìn)度
fileUpload.setProgressListener(uploadProgressListener);//將文件上傳進(jìn)度監(jiān)聽器加入到 fileUpload 中
try {
List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
return parseFileItems(fileItems, encoding);
}
catch (FileUploadBase.SizeLimitExceededException ex) {
throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
}
catch (FileUploadBase.FileSizeLimitExceededException ex) {
throw new MaxUploadSizeExceededException(fileUpload.getFileSizeMax(), ex);
}
catch (FileUploadException ex) {
throw new MultipartException("Failed to parse multipart servlet request", ex);
}
}
}
3.此時(shí),所有需要的類已經(jīng)準(zhǔn)備好,接下來我們需要將 spring 默認(rèn)的文件上傳處理類取消自動(dòng)配置,并將 multipartResolver 指向我們剛剛創(chuàng)建好的繼承 CommonsMultipartResolver 類的自定義文件上傳處理類。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import com.example.listener.CustomMultipartResolver;
/*
* 將 spring 默認(rèn)的文件上傳處理類取消自動(dòng)配置,這一步很重要,沒有這一步,當(dāng)multipartResolver重新指向了我們定義好
* 的新的文件上傳處理類后,前臺(tái)傳回的 file 文件在后臺(tái)獲取會(huì)是空,加上這句話就好了,推測(cè)不加這句話,spring 依然
* 會(huì)先走默認(rèn)的文件處理流程并修改request對(duì)象,再執(zhí)行我們定義的文件處理類。(這只是個(gè)人推測(cè))
* exclude表示自動(dòng)配置時(shí)不包括Multipart配置
*/
@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})
@Configuration
@ComponentScan(basePackages = {"com.example"})
@ServletComponentScan(basePackages = {"com.example"})
public class UploadProgressApplication {
/*
* 將 multipartResolver 指向我們剛剛創(chuàng)建好的繼承 CommonsMultipartResolver 類的自定義文件上傳處理類
*/
@Bean(name = "multipartResolver")
public MultipartResolver multipartResolver() {
CustomMultipartResolver customMultipartResolver = new CustomMultipartResolver();
return customMultipartResolver;
}
public static void main(String[] args) {
SpringApplication.run(UploadProgressApplication.class, args);
}
}
至此,準(zhǔn)備工作完成,我們?cè)賱?chuàng)建一個(gè)測(cè)試用的 controller 和 html 頁(yè)面用于文件上傳。
controller:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/uploadProgress")
public class UploadController {
@RequestMapping(value = "/showUpload", method = RequestMethod.GET)
public ModelAndView showUpload() {
return new ModelAndView("/UploadProgressDemo");
}
@RequestMapping("/upload")
@ResponseBody
public void uploadFile(MultipartFile file) {
System.out.println(file.getOriginalFilename());
}
}
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"></meta>
<title>測(cè)試</title>這里寫代碼片
</head>
<body>
這是文件上傳頁(yè)面
<form action="/uploadProgress/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file"/>
<br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
經(jīng)本人測(cè)試,確實(shí)可以獲取文件上傳進(jìn)度,前臺(tái)頁(yè)面修改進(jìn)度條進(jìn)度可以采用前臺(tái)頁(yè)面輪詢的方式訪問后臺(tái),在相應(yīng)action中通過存儲(chǔ)在session中的對(duì)象 status 來獲取最新的上傳進(jìn)度并返回展示即可。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringCloud解決Feign異步回調(diào)問題(SpringBoot+Async+Future實(shí)現(xiàn))
這篇文章主要介紹了SpringCloud解決Feign異步回調(diào)問題(SpringBoot+Async+Future實(shí)現(xiàn)),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
論java如何通過反射獲得方法真實(shí)參數(shù)名及擴(kuò)展研究
這篇文章主要為大家介紹了java如何通過反射獲得方法的真實(shí)參數(shù)名以及擴(kuò)展研究,有需要的朋友可以借鑒參考下,希望能夠有所幫助祝大家多多進(jìn)步早日升職加薪2022-01-01
Spring中使用JSR303請(qǐng)求約束判空的實(shí)現(xiàn)
這篇文章主要介紹了Spring中使用JSR303請(qǐng)求約束判空的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
基于JavaMail實(shí)現(xiàn)簡(jiǎn)單郵件發(fā)送
這篇文章主要為大家詳細(xì)介紹了基于JavaMail實(shí)現(xiàn)簡(jiǎn)單郵件發(fā)送,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08
java使用Logback配置輸出日志內(nèi)容到文件示例代碼
這篇文章主要介紹了java?Logback輸出日志內(nèi)容到文件,要將logger.info的信息輸出到文件,您可以使用Logback配置,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-09-09

