springboot多附件上传

编程

<!--添加文件上传支持-->

<dependency>

<groupId>commons-io</groupId>

<artifactId>commons-io</artifactId>

<version>2.4</version>

</dependency>

<dependency>

<groupId>commons-fileupload</groupId>

<artifactId>commons-fileupload</artifactId>

<version>1.3.1</version>

</dependency>

<!--添加html5支持-->

<dependency>

<groupId>net.sourceforge.nekohtml</groupId>

<artifactId>nekohtml</artifactId>

</dependency>

 二、相关实体类和方法

文件上传进度实体类

/**

* 文件上传进度

* @author Maochao-zhu

*

*/

public class Progress {

/** 已读字节 **/

private long bytesRead = 0L;

/** 已读MB **/

private String mbRead = "0";

/** 总长度 **/

private long contentLength = 0L;

/****/

private int items;

/** 已读百分比 **/

private String percent;

/** 读取速度 **/

private String speed;

/** 开始读取的时间 **/

private long startReatTime = System.currentTimeMillis();

}

附件类:

package com.cn.zx.po.vo;

/**

* 附件类

* @author Maochao-zhu

*

*/

public class PmFile {

private Integer id;//主键

private Integer objectId;//业务数据ID

private String tableName;//业务数据表名

private String fileName;//文件名

private Long fileSize;//文件大小

private String filePath;//下载路径

private String addTime;//时间

private Long addTimeSecend;

}

/**

* 上传文件信息

* @param pathName

* @param file

* @param request

* @param response

* @return

* @throws IllegalStateException

* @throws IOException

*/

public static Map<String,String> uploadFile(String pathName, MultipartFile file,

HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException{

Map<String,String> map = new HashMap<String,String>();

String realPath = request.getSession().getServletContext().getRealPath("/");

//重新定义文件保存路径

realPath = getRenamePath(realPath, request);

// 文件保存路径

String fileDir = "/fileData/"+pathName+"/" ;

//文件重命名

String fileName = file.getOriginalFilename();

String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

suffix = suffix.trim();

String newFileName = fileName;

if(null!=suffix){

newFileName = DateUtil.getStringAllDate()+"."+suffix;

}

//查看文件是否存在

File destFile = new File(realPath + fileDir);

if (!destFile.exists()) {

destFile.mkdirs();

}

//创建文件

File f = new File(destFile.getAbsoluteFile() + "\" + newFileName);

file.transferTo(f);

f.createNewFile();

String filePath = fileDir + newFileName;

map.put("fileNewName", newFileName);

map.put("fileName", fileName);

map.put("filePath", filePath);

map.put("fileSize", (file.getSize()/1000==0?1:file.getSize()/1000)+"");

map.put("addTime", DateUtil.getStringDate());

return map;

}

/**

* 文件上传Resolver

* @author Maochao-zhu

*/

public class MultipartResolver extends CommonsMultipartResolver {

private HttpServletRequest request;

protected FileUpload newFileUpload(FileItemFactory fileItemFactory) {

ServletFileUpload upload = new ServletFileUpload(fileItemFactory);

upload.setSizeMax(-1);

if (request != null) {

HttpSession session = request.getSession();

FileUploadProgressListener progressListener = new FileUploadProgressListener(session);

upload.setProgressListener(progressListener);

}

return upload;

}

public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {

// 获取到request,要用到session

this.request = request;

return super.resolveMultipart(request);

}

@Override

public MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {

HttpSession session = request.getSession();

String encoding = determineEncoding(request);

FileUpload fileUpload = prepareFileUpload(encoding);

FileUploadProgressListener progressListener = new FileUploadProgressListener(session);

fileUpload.setProgressListener(progressListener);

try {

List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);

return parseFileItems(fileItems, encoding);

} catch (FileUploadBase.SizeLimitExceededException ex) {

throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);

} catch (FileUploadException ex) {

throw new MultipartException("Could not parse multipart servlet request", ex);

}

}

}

/**

* 文件上传进度

* @author Maochao-zhu

*

*/

@Component

public class FileUploadProgressListener implements ProgressListener {

private HttpSession session;

public FileUploadProgressListener() { }

public FileUploadProgressListener(HttpSession session) {

this.session=session;

Progress status = new Progress();

session.setAttribute("upload_ps", status);

}

/**

* pBytesRead 到目前为止读取文件的比特数 pContentLength 文件总大小 pItems 目前正在读取第几个文件

*/

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

Progress status = (Progress) session.getAttribute("upload_ps");

status.setBytesRead(pBytesRead);

status.setContentLength(pContentLength);

status.setItems(pItems);

session.setAttribute("upload_ps", status);

}

}

启动类增加:

/**

* 启动类

*/

//注意取消自动Multipart配置,否则可能在上传接口中拿不到file的值

@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})

@SpringBootApplication

@EnableScheduling

public class SpringbootApplication extends SpringBootServletInitializer {

//注入自定义的文件上传处理类

@Bean(name = "multipartResolver")

public MultipartResolver multipartResolver() {

MultipartResolver multipartResolver = new MultipartResolver();

return multipartResolver;

}

@Override

protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {

return application.sources(SpringbootApplication.class);

}

public static void main(String[] args) {

SpringApplication.run(SpringbootApplication.class, args);

}

}

html页面引入多附件组件 

一、实体类继承BasePo类获取附件参数:filePath

二、html页面引入:

<iframe name="fileInfo" id="fileInfo" width="100%" height="200px;" frameborder="0"

th:src="@{/file/goFileUpload(objectId=${out.id},tableName="emailOut",canEdit="false")}"></iframe>

参数说明:

objectId:功能表ID

tableName:上传附件的功能表标识 tableName

canEdit:是否显示上传文件按钮 true表示显示上传文件按钮/false表示不显示上传文件按钮

三、JS文件中增加fileUploadArray获取上传组件中的文件信息,传递到后台

参数定义:

var fileUploadArray;

参数获取:

if(fileUploadArray){

obj.field.filePath = fileUploadArray.join(",");

}

四、新增附件后台Controller增加

@Resource

PmFileService pmFileService;

方法中引入:

if(filePath!=null){

pmFileService.addPmFileByObjectInsert(objectId,tableName,filePath);

}

参数说明:

objectId:功能表ID

tableName:上传附件的功能表标识 tableName

filePath:前端上传文件信息

 

以上是 springboot多附件上传 的全部内容, 来源链接: utcz.com/z/515268.html

回到顶部