Это был просто еще один длинный день в офисе с недоступной базой данных, и один из членов команды отстал на неделю. Таким образом, мы должны были работать в команде, чтобы получить его. Весной 3 было очень удобно загрузить файл. Тем не менее, было мало помощи, чтобы загрузить несколько файлов из файла JSP.
Для загрузки нескольких файлов необходимо выполнить три основных действия:
a) JSP должен иметь элементы input [file], переданные в виде массива.
|
1
2
|
<td><input name="fileData[0]" id="image0" type="file" /></td><td><input name="fileData[1]" id="image1" type="file" /></td> |
б) Объект ModelAttribute / Model в Spring MVC должен иметь список MultipartFile.
|
1
2
3
4
5
|
import java.util.List;import org.springframework.web.multipart.commons.CommonsMultipartFile;public class UploadItem { private String filename; private List<CommonsMultipartFile> fileData; |
c) Сконфигурируйте компонент Multipart Resolver в dispatcher-servlet.xml [applicationContext-servlet.xml]
|
1
2
3
|
<!-- Configure the multipart resolver --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean> |
г) Логика для чтения файлов из модели и сохранения ее в папке на уровне контроллера.
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
@RequestMapping(method = RequestMethod.POST)public String create(UploadItem uploadItem, BindingResult result,HttpServletRequest request, HttpServletResponse response,HttpSession session) {if (result.hasErrors()) {for (ObjectError error : result.getAllErrors()) {System.err.println("Error: " + error.getCode() + " - "+ error.getDefaultMessage());}return "/uploadfile";}// Some type of file processing...System.err.println("-------------------------------------------");try {for(MultipartFile file:uploadItem.getFileData()){String fileName = null;InputStream inputStream = null;OutputStream outputStream = null;if (file.getSize() > 0) {inputStream = file.getInputStream();if (file.getSize() > 20000) {System.out.println("File Size exceeded:::" + file.getSize());return "/uploadfile";}System.out.println("size::" + file.getSize());fileName = request.getRealPath("") + "/images/"+ file.getOriginalFilename();outputStream = new FileOutputStream(fileName);System.out.println("fileName:" + file.getOriginalFilename());int readBytes = 0;byte[] buffer = new byte[10000];while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {outputStream.write(buffer, 0, readBytes);}outputStream.close();inputStream.close();// ..........................................session.setAttribute("uploadFile", file.getOriginalFilename());}//MultipartFile file = uploadItem.getFileData();}} catch (Exception e) {e.printStackTrace();}return "redirect:/forms/uploadfileindex";} |
Я расширил пример, который найден @ RoseIndia, для динамического создания файловых узлов и отправки их на контроллер.
Просто скачайте исходный код и замените приведенный ниже файл jsp и внесите другие необходимые изменения:
Upload.jsp
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
<%@page contentType="text/html;charset=UTF-8"%><%@page pageEncoding="UTF-8"%><%@ page session="false"%><html><head><META http-equiv="Content-Type" content="text/html;charset=UTF-8"><title>Upload Example</title><script language="JavaScript">var count=0;function add(type) {//Create an input type dynamically.var table = document.getElementById("fileUploadTable");var tr = document.createElement("tr");var td = document.createElement("td");var element = document.createElement("input");//Assign different attributes to the element.element.setAttribute("type", "file");element.setAttribute("value", "");element.setAttribute("name", "fileData["+type+"]");//Append the element in page (in span).td.appendChild(element);tr.appendChild(td);table.appendChild(tr);}function Validate(){var image =document.getElementById("image").value;if(image!=''){var checkimg = image.toLowerCase();if (!checkimg.match(/(\.jpg|\.png|\.JPG|\.PNG|\.jpeg|\.JPEG)$/)){alert("Please enter Image File Extensions .jpg,.png,.jpeg");document.getElementById("image").focus();return false;}}return true;}</script></head><body><form:form modelAttribute="uploadItem" name="frm" method="post"enctype="multipart/form-data" onSubmit="return Validate();"><fieldset><legend>Upload File</legend><table ><tr><input type="button" name="Add Image" onclick="add(count++)" value="Add Image"/></tr><tr><table id="fileUploadTable"><!--td><form:label for="fileData" path="fileData">File</form:label><br /></td><td><input name="fileData[0]" id="image0" type="file" /></td><td><input name="fileData[1]" id="image1" type="file" /></td--></table></tr><tr><td><br /></td><td><input type="submit" value="Upload" /></td></tr></table></fieldset></form:form></body></html> |
UploadItem.java, сгенерируйте методы getter и setter для приватного файла ListData ;, UploadFileController.java, а затем просто скопируйте и вставьте create (…), упомянутый в блоге выше.
Примечание. Если у вас по-прежнему возникают проблемы с загрузкой файлов в Spring MVC, добавьте MultipartFilter. Обратитесь сюда .
|
1
2
3
4
5
6
7
8
|
<filter><filter-name>multipartFilter</filter-name><filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class></filter><filter-mapping><filter-name>multipartFilter</filter-name><url-pattern>/springrest/*</url-pattern></filter-mapping> |
|
1
2
3
4
5
|
<bean id="filterMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="maxUploadSize"><value>10000000</value></property></bean> |
Ссылка: Загрузите несколько файлов в Spring MVC 3 от нашего партнера JCG Сриниваса Овна в блоге Bemused.