springboot多附件上傳

1、在 pom.xml中增長相關jar包html

<!--添加文件上傳支持-->
        <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>

 2、相關實體類和方法前端

文件上傳進度實體類
 

/**
 *  文件上傳進度
 * @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頁面引入多附件組件 html5

1、實體類繼承BasePo類獲取附件參數:filePath
	2、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表示不顯示上傳文件按鈕
	3、JS文件中增長fileUploadArray獲取上傳組件中的文件信息,傳遞到後臺
		參數定義:
			var fileUploadArray;
		參數獲取:
			if(fileUploadArray){
				obj.field.filePath = fileUploadArray.join(',');
			}
	4、新增附件後臺Controller增長
	    @Resource
		PmFileService pmFileService;
		
		方法中引入:
			if(filePath!=null){
			   pmFileService.addPmFileByObjectInsert(objectId,tableName,filePath);
			}
		參數說明:
			objectId:功能表ID
			tableName:上傳附件的功能表標識 tableName
			filePath:前端上傳文件信息
相關文章
相關標籤/搜索