欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

如何在SpringBoot中使用fileUpload獲取文件的上傳進(jìn)度

這篇文章將為大家詳細(xì)講解有關(guān)如何在SpringBoot中使用fileUpload獲取文件的上傳進(jìn)度,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

公司主營業(yè)務(wù):成都做網(wǎng)站、成都網(wǎng)站制作、移動網(wǎng)站開發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實(shí)現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競爭能力。創(chuàng)新互聯(lián)建站是一支青春激揚(yáng)、勤奮敬業(yè)、活力青春激揚(yáng)、勤奮敬業(yè)、活力澎湃、和諧高效的團(tuán)隊(duì)。公司秉承以“開放、自由、嚴(yán)謹(jǐn)、自律”為核心的企業(yè)文化,感謝他們對我們的高要求,感謝他們從不同領(lǐng)域給我們帶來的挑戰(zhàn),讓我們激情的團(tuán)隊(duì)有機(jī)會用頭腦與智慧不斷的給客戶帶來驚喜。創(chuàng)新互聯(lián)建站推出重慶免費(fèi)做網(wǎng)站回饋大家。

本功能基于commons fileUpload 組件實(shí)現(xiàn)

1.首先,不能在程序中直接使用 fileUpload.parseRequest(request)的方式來獲取 request 請求中的 multipartFile 文件對象,原因是因?yàn)樵?spring 默認(rèn)的文件上傳處理器 multipartResolver 指向的類CommonsMultipartResolver 中就是通過 commons fileUpload 組件實(shí)現(xiàn)的文件獲取,因此,在代碼中再次使用該方法,是獲取不到文件對象的,因?yàn)榇藭r的 request 對象是不包含文件的,它已經(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 方法,在此之前,我們需要創(chuàng)建一個實(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 到目前為止讀取文件的比特數(shù) pContentLength 文件總大小 pItems 目前正在讀取第幾個文件 
   */ 
  @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;  //到目前為止讀取文件的比特數(shù)  
  private long pContentLength = 0L;  //文件總大小  
  private int pItems;        //目前正在讀取第幾個文件 

  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用于存儲上傳進(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.此時,所有需要的類已經(jīng)準(zhǔn)備好,接下來我們需要將 spring 默認(rèn)的文件上傳處理類取消自動配置,并將 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)multipartResolver重新指向了我們定義好
 * 的新的文件上傳處理類后,前臺傳回的 file 文件在后臺獲取會是空,加上這句話就好了,推測不加這句話,spring 依然
 * 會先走默認(rèn)的文件處理流程并修改request對象,再執(zhí)行我們定義的文件處理類。(這只是個人推測)
 * exclude表示自動配置時不包括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)備工作完成,我們再創(chuàng)建一個測試用的 controller 和 html 頁面用于文件上傳。

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>測試</title>這里寫代碼片
</head>
<body>
  這是文件上傳頁面
  <form action="/uploadProgress/upload" method="POST" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <br/>
    <input type="submit" value="提交"/>
  </form>
</body>
</html>

關(guān)于如何在SpringBoot中使用fileUpload獲取文件的上傳進(jìn)度就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

網(wǎng)站名稱:如何在SpringBoot中使用fileUpload獲取文件的上傳進(jìn)度
標(biāo)題網(wǎng)址:http://chinadenli.net/article42/pgpoec.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供建站公司移動網(wǎng)站建設(shè)ChatGPT小程序開發(fā)網(wǎng)站制作網(wǎng)站導(dǎo)航

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

搜索引擎優(yōu)化