SpringBoot+fileUpload获取文件上传进度

我本人在网上找了很多关于文件上传进度获取的文章,普遍基于spring MVC 框架通过 fileUpload 实现,对于spring Boot 通过 fileUpload 实现的帖子非常少,由于小弟学艺不精,虽然 Spring Boot 和 Spring MVC 相差不大,只是配置方式的差别,还是搞了很久,上传此文章的目的是希望自己作为文本保留,以便日后查看备忘,并且希望通过我的例子可以帮助到其他人而已,如果各位大佬发现小弟对于某些知识有误解,还请不吝赐教,先谢谢各位前辈了!

写此篇文章之前我查了很多关于spring MVC 框架通过 fileUpload 实现进度条的帖子和文章,在此对各位作者表示感谢!

此方法有一个问题,很严重的问题,就是只能获取当前服务器上传的总进度,没法分用户计算,不知道哪位前辈有办法分用户计算,烦请不吝赐教,谢谢各位前辈!

本功能基于commons fileUpload 组件实现

1.首先,不能在程序中直接使用 fileUpload.parseRequest(request)的方式来获取 request 请求中的 multipartFile 文件对象,原因是因为在 spring 默认的文件上传处理器 multipartResolver 指向的类CommonsMultipartResolver 中就是通过 commons fileUpload 组件实现的文件获取,因此,在代码中再次使用该方法,是获取不到文件对象的,因为此时的 request 对象是不包含文件的,它已经被CommonsMultipartResolver 类解析处理并转型。

CommonsMultipartResolver 类中相关源码片段:

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 文件上传进度监听器,所以,直接使用 CommonsMultipartResolver 类是无法监听文件上传进度的,如果我们需要获取文件上传进度,就需要继承 CommonsMultipartResolver 类并重写 parseRequest 方法,在此之前,我们需要创建一个实现了 processListener 接口的实现类用于监听文件上传进度。

processListener接口实现类:

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 到目前为止读取文件的比特数 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 实体类:

import org.springframework.stereotype.Component;

@Component
public class ProgressEntity {  
    private long pBytesRead = 0L;   //到目前为止读取文件的比特数   
    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());//问文件上传进度监听器设置session用于存储上传进度
		fileUpload.setProgressListener(uploadProgressListener);//将文件上传进度监听器加入到 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.此时,所有需要的类已经准备好,接下来我们需要将 spring 默认的文件上传处理类取消自动配置,并将 multipartResolver 指向我们刚刚创建好的继承 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 默认的文件上传处理类取消自动配置,这一步很重要,没有这一步,当multipartResolver重新指向了我们定义好
 * 的新的文件上传处理类后,前台传回的 file 文件在后台获取会是空,加上这句话就好了,推测不加这句话,spring 依然
 * 会先走默认的文件处理流程并修改request对象,再执行我们定义的文件处理类。(这只是个人推测)
 * exclude表示自动配置时不包括Multipart配置
 */
@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})

@Configuration
@ComponentScan(basePackages = {"com.example"})
@ServletComponentScan(basePackages = {"com.example"})
public class UploadProgressApplication {

/*
 * 将 multipartResolver 指向我们刚刚创建好的继承 CommonsMultipartResolver 类的自定义文件上传处理类
 */
@Bean(name = "multipartResolver")
public MultipartResolver multipartResolver() {
	CustomMultipartResolver customMultipartResolver = new CustomMultipartResolver();
	return customMultipartResolver;
}

public static void main(String[] args) {
	SpringApplication.run(UploadProgressApplication.class, args);
}
}

至此,准备工作完成,我们再创建一个测试用的 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>

经本人测试,确实可以获取文件上传进度,前台页面修改进度条进度可以采用前台页面轮询的方式访问后台,在相应action中通过存储在session中的对象 status 来获取最新的上传进度并返回展示即可。

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 15
    评论
<h3>回答1:</h3><br/>如何实现SpringBoot+Vue文件上传文件上传涉及前端和后端两个方面的实现。 前端的Vue代码: 1. 定义上传文件的模板: ``` <template> <div> <input type="file" @change="handleFileUpload" ref="fileUpload"> <button @click="submitFile">上传文件</button> </div> </template> ``` 2. 在Vue的methods中添加上传文件的方法: ``` methods: { handleFileUpload () { this.file = this.$refs.fileUpload.files[0] }, submitFile () { let formData = new FormData() formData.append('file', this.file) axios.post('/api/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(response => { console.log(response.data) }) } } ``` 这个方法中,我们通过FormData对象来将文件对象上传到服务器端。需要注意的是,在axios请求中,我们需要指定Content-Type为multipart/form-data,以便后端能够正确地解析上传的文件。 后端的SpringBoot代码: 1. 配置文件上传的Multipart配置 在application.properties文件中添加以下配置: ``` spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB ``` 这个配置指定了上传文件的大小限制,例如,上限设置为10MB。 2. 添加文件上传的Controller ``` @RestController @RequestMapping("/api") public class FileUploadController { @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { try { // 将上传的文件保存到指定路径下 String filePath = "C:/uploads/" + file.getOriginalFilename(); file.transferTo(new File(filePath)); return "文件上传成功"; } catch (IOException e) { e.printStackTrace(); return "文件上传失败"; } } } ``` 这个Controller中,通过@RequestParam注解来指定上传的文件参数名,再通过MultipartFile获取上传的文件。最后,将文件保存到指定的路径下。需要注意的是,保存路径需要在业务中合理设置。 至此,SpringBoot+Vue文件上传的实现就完成了。 <h3>回答2:</h3><br/>Spring Boot是一个广受欢迎的Java开发框架,Vue是一款流行的前端开发框架,他们之间的结合可以为用户提供高效、易用的Web应用程序。在其中,文件上传是Web应用程序的必备功能之一。Spring Boot和Vue的结合可使文件上传实现更加轻松快捷。 首先,需要在前端部分使用Vue来创建一个简单的文件上传组件,该组件可以实现文件选择、文件上传以及进度条的显示等功能。可以使用vue-file-upload或者其他类似的第三方库来实现文件上传功能,同时需要在该组件中设置上传API的路径和上传的文件名。 然后,需要在后端部分使用Spring Boot来处理上传的文件。Spring Boot提供了丰富的文件处理工具和API,可以轻松地实现文件上传。可以使用Spring Boot的MultipartResolver来解析文件上传请求,同时可以使用MultipartFile类来获取上传的文件对象。 接着,需要在Spring Boot的Controller中创建一个上传接口用于处理文件上传请求。该接口需要使用@RequestParam注解来获取上传的文件对象,并使用MultipartFile类来处理文件上传。同时,还需要设置上传文件的路径,并将上传成功后的文件路径返回到前端。 最后,需要在前端页面使用Vue来处理上传结果。根据上传返回的结果,可以在页面上显示上传成功或者上传失败的提示信息。同时,还可以使用Vue实现进度条的动态更新,用以提醒用户当前的上传状态。 总的来说,Spring Boot和Vue的结合可以实现快速、高效的文件上传功能。借助两个框架提供的强大工具和API,开发者可以轻松地实现文件上传功能,提高Web应用程序的可靠性和用户体验。 <h3>回答3:</h3><br/>SpringBoot是一个基于Spring框架的快速开发微服务的工具,它简化了Spring框架的配置,使开发者可以快速上手。Vue是一款流行的前端框架,它具有高效的组件化开发和数据双向绑定等优点。在实现文件上传功能时,可以结合使用SpringBoot和Vue来实现。 首先,需要在SpringBoot的依赖管理文件pom.xml中添加对spring-boot-starter-web和spring-boot-starter-test的引用: ``` <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> ``` 然后,在SpringBoot的配置文件application.properties中添加文件上传的配置: ``` spring.servlet.multipart.enabled=true spring.servlet.multipart.max-file-size=200MB spring.servlet.multipart.max-request-size=215MB ``` 接下来,在SpringBoot的Controller中编写文件上传接口: ``` @RestController @RequestMapping("/api") @CrossOrigin(origins = "*", maxAge = 3600) public class UploadController { @PostMapping("/upload") public ResponseResult upload(@RequestParam("file") MultipartFile file) { // 处理文件上传业务逻辑 } } ``` 在Vue的组件中,可以使用vue-axios实现文件上传: ``` <template> <div> <input type="file" @change="uploadFile" /> </div> </template> <script> import axios from 'axios'; export default { data() { return { file: null } }, methods: { uploadFile() { let formData = new FormData(); formData.append('file', this.file); axios.post('http://localhost:8080/api/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(res => { console.log(res.data); }) .catch(error => { console.log(error); }) } } } </script> ``` 其中,formData为提交的表单数据,append方法将文件对象添加到表单中。axios.post方法发送POST请求,在请求头中设置Content-Type为multipart/form-data。 总体来说,使用SpringBoot和Vue实现文件上传功能比较简单。通过配置SpringBoot文件上传参数和编写文件上传接口,配合Vue的文件上传组件,即可实现文件的上传功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值