java spring 上传文件_springboot实现文件上传实时进度(单文件)

1.pom.xml文件中导入包。

commons-fileupload

commons-fileupload

1.4

2.在配置文件中对上传文件的参数进行配置

resource.path=xx/xx/xx/xx/(写你自己要上传文件到的文件夹路径)

还可以配置允许上传的最大文件数等配置,需要的话百度一下。

3.编写配置类

FileUploadProgressListener.java

思路是把文件上传的进度在后台算出来,存在session中,前台定时任务一直请求后台将进度实时返回。

import org.apache.commons.fileupload.ProgressListener;

import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;

@Component

public class FileUploadProgressListener implements ProgressListener {

private HttpSession session;

public void setSession(HttpSession session) {

this.session = session;

session.setAttribute("upload_percent", 0);

}

@Override

public void update(long pBytesRead, long pContentLength, int pItems) {

int percent = (int) (pBytesRead * 100.0 / pContentLength);

session.setAttribute("upload_percent", percent);

}

}

CustomMultipartResolver.java

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUpload;

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.MultipartException;

import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;

import java.util.List;

public class CustomMultipartResolver extends CommonsMultipartResolver {

@Autowired

private FileUploadProgressListener listener;

@Override

protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {

String encoding = determineEncoding(request);

FileUpload fileUpload = prepareFileUpload(encoding);

fileUpload.setProgressListener(listener);

listener.setSession(request.getSession());

try {

List fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);

return parseFileItems(fileItems, encoding);

}catch (FileUploadException ex) {

throw new MultipartException("Failed to parse multipart servlet request", ex);

}

}

}

BeanConfig.java

import com.demo.jin.demo.config.CustomMultipartResolver;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.multipart.MultipartResolver;

@Configuration

public class BeanConfig {

@Bean(name = "multipartResolver")

public MultipartResolver multipartResolver()

{

return new CustomMultipartResolver();

}

}

上面这几个配置类都是要用到 commons-fileupload需要的,百度一下,大同小异。

controller层

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

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

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.RequestParam;

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

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;

import java.io.File;

import java.io.FileOutputStream;

import java.util.Calendar;

@Controller

public class fileuploadController {

@Value("${resource.path}")

private String resourcePath; //配置的上传路径

private static final Logger logger = LoggerFactory.getLogger(fileuploadController.class);

/**

* 上传文件的页面

* @return

*/

@RequestMapping(value = "/uploadPage")

public String uploadPage(){

return "uploadPage";

}

/**

* 处理文件上传

*/

@RequestMapping(value="/upload", method = RequestMethod.POST)

@ResponseBody

public String uploadImg(@RequestParam("file") MultipartFile file,HttpServletRequest request) {

Calendar cal = Calendar.getInstance();

Integer year = cal.get(Calendar.YEAR);

Integer month = cal.get(Calendar.MONTH)+1;

Integer day = cal.get(Calendar.DAY_OF_MONTH);

String msg = "SUCCESS";

String fileName = file.getOriginalFilename();

//该路径可以从文件中读取,此处演示略

String filePath = resourcePath + File.separator + year + File.separator + month + File.separator + day + File.separator;

System.out.println("上传路径:"+filePath);

try {

uploadFile(file.getBytes(), filePath, fileName);

} catch (Exception e) {

msg = e.getMessage();

}

//返回json

return msg;

}

/**

* @Description : 上传文件

* @param file : 文件实体

* @param filePath : 文件目标路径

* @param fileName : 文件名

* @throws Exception

*/

public void uploadFile(byte[] file, String filePath, String fileName) throws Exception {

File targetFile = new File(filePath);

if(!targetFile.exists()){

targetFile.mkdirs();

}

FileOutputStream out = new FileOutputStream(filePath+fileName);

out.write(file);

out.flush();

out.close();

}

@RequestMapping(value = "/uploadStatus")

@ResponseBody

public Integer uploadStatus(HttpServletRequest request){

HttpSession session = request.getSession();

Object percent = session.getAttribute("upload_percent");

return null != percent ? (Integer) percent : 0;

}

}

前台页面

uploadPage,html

测试

#parent{border:1px #EEE solid;width: 500px;height: 30px;margin: 0 auto;}

#child{width: 0%;height: 30px;background-color: lime;}

p{text-align: center;color: fuchsia;}

.file {

position: relative;

display: inline-block;

background: #D0EEFF;

border: 1px solid #99D3F5;

border-radius: 4px;

padding: 4px 12px;

overflow: hidden;

color: #1E88C7;

text-decoration: none;

text-indent: 0;

line-height: 20px;

}

.file input {

position: absolute;

font-size: 100px;

right: 0;

top: 0;

opacity: 0;

}

.file:hover {

background: #AADFFD;

border-color: #78C3F3;

color: #004974;

text-decoration: none;

}

function upload() {

$("#form").ajaxSubmit(function(message) {

});

// 100ms 打印一次当前的上传进度

var update=setInterval(function () {

var flag = false;

$.ajax({

type:"get",

dataType: 'json',

url:"/uploadStatus",

success: function(result){

$("#info").text("正在上传:"+result+"%");

$("#child").width(result+"%");

if(result==100){

//清除定时器,停止更新

flag = true;

if(flag){

clearInterval(update);

console.log("恭喜,更新成功!");

$("#info").text("上传成功:"+result+"%");

}

}

console.log(result);

}

});

}, 100);

return false;

}

样式都是网上找的。

只实现了单文件的上传,多文件的可以在这个基础上改一下。

本文地址:https://blog.csdn.net/TqingqingT/article/details/107354304

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:深蓝海洋 设计师:CSDN官方博客 返回首页
评论

打赏作者

爱家小厨酱

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值