1. 程式人生 > >使用FormData進行Ajax請求上傳檔案到controller層的實現

使用FormData進行Ajax請求上傳檔案到controller層的實現

需求背景:

頁面上傳一個檔案到controller層,然後後臺對檔案進行處理。檔案型別不限

第一種:單純的上傳檔案

頁面功能展現:


第一步:首先需要兩個jar

commons-fileupload-1.3.2.jar
commons-io-2.
4.jar

版本不限:

pom檔案中相應兩個jar:

	<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</version>
	</dependency>

第二步:在spring-mvc.xml中配置

    <!-- 檔案上傳配置 -->
    <bean id="multipartResolver" 
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 上傳的最大限制 -->
		<property name="maxUploadSize" value="209715200" />
		<!-- 預設編碼 -->
		<property name="defaultEncoding" value="UTF-8" />
		<!-- 上傳檔案的解析 -->
		<property name="resolveLazily" value="true" />
    </bean>

第三步:jsp頁面程式碼

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8" />
    <title>資料生成</title>
</head>
<body>
	<div>
		<form method="post" id="file" action="" enctype="multipart/form-data">
		    <h3>選擇一個檔案:</h3>
		    <input id="excelFile" type="file" name="uploadFile" />
		    <br/><br/>
		    <input type="button" value="上傳" onclick="uploadFiles();"/>
		</form>
	</div>
</body>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function uploadFiles(){  
// 	var uploadFile = $('#excelFile').get(0).files[0];
	var uploadFile = new FormData($("#file")[0]);
	console.log(uploadFile);
	if("undefined" != typeof(uploadFile) && uploadFile != null && uploadFile != ""){
		$.ajax({
			url:'/manage/fileupload/upload',
			type:'POST',
			data:uploadFile,
			async: false,  
			cache: false, 
			contentType: false, //不設定內容型別
			processData: false, //不處理資料
			success:function(data){
				console.log(data);
				alert(data.msg);
			},
			error:function(){
				alert("上傳失敗!");
			}
		})
	}else {
		alert("選擇的檔案無效!請重新選擇");
	}
}   
</script>
</html>
有關於FormData可參考此連結:
https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects

第四步:controller層程式碼

package com.bigaoread.platform.web.manage.fileupload;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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 com.bigaoread.platform.service.fileupload.FileUploadService;

@Controller
@RequestMapping("/manage/fileupload")
public class FileUploadController {
	private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);
	
	@Autowired
	private FileUploadService fileUploadService;
	
	@RequestMapping("/uploadPage")
	public String uploadPage() {
		return "/manage/fileupload/uploadPage";
	}
	
	@RequestMapping(value="/upload", method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> uploadFile(HttpServletRequest request,
			@RequestParam MultipartFile uploadFile){
		Map<String,  Object> resultMap = new HashMap<>();
		resultMap = fileUploadService.uploadFile(uploadFile);
		return resultMap;
	}

}

第五步:debug測試

上傳檔案 表結構原始.docx


點選上傳後,後臺debug檢視物件:


上傳成功!

第二種,假如在前端還要傳入其他引數時的做法

情景圖(增加了一個下拉選):


這種多一個引數時,則需要修改兩個地方就好了。

第一個是JSP:

如:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%-- <%@ page language="java" contentType="text/html; charset=UTF-8" --%>
<%-- 	pageEncoding="UTF-8" import="java.util.*" isELIgnored="false"%> --%>
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8" />
    <title>資料生成</title>
</head>
<body>
	<div>
		<form method="post" id="file" action="" enctype="multipart/form-data">
			<select id="select">
				<option value="1">1</option>
				<option value="2">2</option>
				<option value="3">3</option>
				<option value="4">4</option>
				<option value="5">5</option>
			</select>
		    <h3>選擇一個檔案:</h3>
		    <input id="excelFile" type="file" name="uploadFile" />
		    <br/><br/>
		    <input type="button" value="上傳" onclick="uploadFiles();"/>
		</form>
	</div>
</body>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function uploadFiles(){  
	var formData = new FormData();
	var uploadFile = $('#excelFile').get(0).files[0];
	// 	var uploadFile = new FormData($("#file")[0]);
	var selectedId = $('#select').val();
	formData.append("uploadFile",uploadFile);
	formData.append("selectedId", selectedId);
	console.log(uploadFile);
	if("undefined" != typeof(uploadFile) && uploadFile != null && uploadFile != ""){
		$.ajax({
			url:'/manage/fileupload/upload',
			type:'POST',
			data:formData,
			async: false,  
			cache: false, 
			contentType: false, //不設定內容型別
			processData: false, //不處理資料
			success:function(data){
				console.log(data);
				alert(data.msg);
			},
			error:function(){
				alert("上傳失敗!");
			}
		})
	}else {
		alert("選擇的檔案無效!請重新選擇");
	}
}   
</script>
</html>

controller程式碼:

package com.bigaoread.platform.web.manage.fileupload;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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 com.bigaoread.platform.service.fileupload.FileUploadService;

@Controller
@RequestMapping("/manage/fileupload")
public class FileUploadController {
	private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);
	
	@Autowired
	private FileUploadService fileUploadService;
	
	@RequestMapping("/uploadPage")
	public String uploadPage() {
		return "/manage/fileupload/uploadPage";
	}
	
	@RequestMapping(value="/upload", method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> uploadFile(HttpServletRequest request,
			@RequestParam MultipartFile uploadFile) throws IOException{
		String selectedId = request.getParameter("selectedId");
		Map<String,  Object> resultMap = new HashMap<>();
		resultMap = fileUploadService.uploadFile(uploadFile);
		return resultMap;
	}

}

測試效果:


結果: