SpringMVC實現文件上傳multipartResolver

1、導入相關依賴

<!-- 文件上傳 -->
<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.3.2</version>
</dependency>

2、配置文件上傳參數

<!-- 配置文件上傳的參數 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<property name="defaultEncoding" value="utf-8"></property>
	<property name="maxUploadSize" value="104857600"></property>
	<!-- 最大上傳文件大小:  104857600/1024=102400K=100M-->
	<property name="maxInMemorySize" value="40480"></property>
	<!-- 設置一個大小,multipart請求小於這個大小時會存到內存中,大於這個內存會存到硬盤中,默認爲1024 -->
</bean>

3、編寫監聽器InitApplicationListener.java

在程序啓動時,創建一下保存上傳文件的文件夾

package com.hx.skyDrive.listener;

import java.io.File;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import com.hx.skyDrive.util.StringUtil;
/**
 * 用來創建該項目文件上傳的存放目錄
 * @author Huathy
 * @date 2020年3月14日
 */
@WebListener
public class InitApplicationListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		String path = "../files";
		
		String temp = sce.getServletContext().getInitParameter("filesPath");
		
		if( !StringUtil.checkNull(temp) ){
			path = temp;
		}
		
		String basePath  = sce.getServletContext().getRealPath("/");
		File fl = new File(basePath + path);
		if( !fl.exists() ){
			fl.mkdirs();
		}
	}
}

4、編寫文件上傳的控制器FileController.java

package com.hx.skyDrive.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件管理類
 * @author Huathy
 * @time 2020年3月23日  下午8:41:45
 */
@RestController
@RequestMapping("/file")
public class FileController {
	
	/**
	 * 文件上傳方法
	 * @param fl
	 * @param req
	 * @return
	 */
	@RequestMapping("upload")
	public int upload(@RequestParam("file")MultipartFile fl , HttpServletRequest req) {
		int result = -1;
		if(uid == null || uid<=0){
			return -3;	//未登錄
		}
		
		if(fl.isEmpty()){
			return -2;	//請選擇需要上傳的文件
		}
		
		String fName = fl.getOriginalFilename().trim();
		Long size = fl.getSize();
		
		if(flBiz.isFileExist(fName,size)){
			return -4;	//文件已存在,請勿重複上傳
		}
		
		try {
			String savePath = "../files";
			String path = req.getRealPath("");
			String temp = req.getServletContext().getInitParameter("filesPath");
			if( temp!=null && !"".equals(temp) ){	//這裏對temp進行判空
				savePath = temp;
			}
			
			savePath += "/" + new Date().getTime() + "-" + fName ;
			
			File dest = new File(path, savePath);
			fl.transferTo(dest);	//將文件上傳到服務器
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}	
		return result;
	}	
}

5、前端HTML與JS代碼

  1. HTML
<form id="uploadForm">
	<input type="file" name="file" id="file">
	<button type="button" id="fileUploadBtn" class="layui-btn layui-btn-warm">上傳資源</button>
</form>
  1. js:
/******** 文件上傳的方法 *************************************/
$('#fileUploadBtn').click(function fileUpload(){
	var fl = $('#file')[0].value;
	if( !fl ){
		layer.msg('操作失誤,請選擇需要上傳的文件...');
		return ;
	}
	var formData = new FormData($('#uploadForm')[0]);
	
	var index = layer.load(1, {shade: false}); //顯示等待圖標。。
	layer.msg('文件上傳中...');		//提示
	
	$.ajax({
		type : 'post' ,
		url : 'file/upload' ,
		data : formData ,
		cache : false ,
		processData : false,
		contentType : false,
		success : function(data,status){
			data = parseInt($.trim(data));
			layer.closeAll();	//關閉所有窗口
			if( data > 0 ){
				layer.msg('上傳成功😀,待管理員審覈...');
				$('#uploadForm')[0].reset();
			}else if( data == -2 ){
				layer.msg('上傳失敗-請選擇需要上傳的文件..');
			}else if( data == -3 ){
				layer.msg('請先登錄,後再上傳文件..');
				setTimeout(function(){
					$('#showLoginBtn').click();
				},800);
			}else if( data == -4 ){
				layer.msg('該文件已存在,請勿重複上傳!!');
			}else{
				layer.msg('上傳失敗😭');
			}
			
		},
		error : function(data,status,e){
			layer.closeAll();	//關閉所有窗口
			layer.alert('上傳失敗'+e +"\n 本站最大文件上傳大小爲100M,請檢查上傳文件大小..");
		}
	});
	return false;
});

終:在tomcat的該項目的上級目錄中可以看到已上傳的文件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章