Spring MVC 3:上傳多個文件

只是在辦公室又漫長的一天,數據庫不可用,一個團隊成員現在滯后一周。 因此,我們必須作為一個團隊來交付它。 在Spring3,它看起來很直接上傳文件。 但是,從jsp文件上載多個文件幾乎沒有幫助。

上載多個文件需要完成三件事:

a)JSP需要將input [file]元素作為數組傳遞。

<td><input name="fileData[0]" id="image0" type="file" /></td>
<td><input name="fileData[1]" id="image1" type="file" /></td>

b)Spring MVC中的ModelAttribute / Model對象需要具有MultipartFile的列表。

import java.util.List;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public class UploadItem {private String filename;private List<CommonsMultipartFile> fileData;

c)在dispatcher-servlet.xml [applicationContext-servlet.xml]中配置Multipart Resolver bean

<!-- Configure the multipart resolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>

d)從模型讀取文件并將其存儲在Controller層的文件位置中的邏輯。

@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發現的示例,以動態創建文件節點并將其發布到Controller。

只需下載源代碼并替換下面的jsp文件并進行其他必要的更改:

Upload.jsp

<%@page contentType="text/html;charset=UTF-8"%>
<%@page pageEncoding="UTF-8"%>
<%@ page session="false"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%><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,為私有List fileData;,UploadFileController.java生成getter和setter方法,然后僅復制并粘貼上面博客中提到的create(…)。

注意:如果在Spring MVC中文件上傳仍然遇到問題,請添加MultipartFilter。 請參考這里 。

<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>
<bean id="filterMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>10000000</value>
</property>
</bean>

參考:在Bemused博客上,從我們的JCG合作伙伴 Srinivas Ovn 在Spring MVC 3中上傳多個文件 。

翻譯自: https://www.javacodegeeks.com/2013/01/spring-mvc-3-upload-multiple-files.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/370144.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/370144.shtml
英文地址,請注明出處:http://en.pswp.cn/news/370144.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

spring 事務隔離級別和傳播行為_Spring事務傳播性與隔離性實戰

一、事務傳播性1.1 什么是事務的傳播性事務的傳播性一般在事務嵌套時候使用&#xff0c;比如在事務A里面調用了另外一個使用事務的方法&#xff0c;那么這倆個事務是各自作為獨立的事務執行提交&#xff0c;還是內層的事務合并到外層的事務一塊提交那&#xff0c;這就是事務傳播…

前端為什么非要動靜分離 說一下CDN托管的意義

大型Web應用對速度的追求并沒有止步于僅僅利用瀏覽器緩存&#xff0c;因為瀏覽器緩存始終只是為了提升二次訪問的速度&#xff0c;對于首次訪問的加速&#xff0c;我們需要從網絡層面進行優化&#xff0c;最常見的手段就是CDN&#xff08;Content Delivery Network&#xff0c;…

unity語音聊天之 www.GetAudioClip

最近在開發語音聊天功能,游戲需要跨平臺安卓與ios&#xff0c;上傳本地錄制的wav文件至服務器后&#xff0c;需要根據服務器返回的地址進行語音文件的下載并進行播放。 這里通過使用www進行下載并播放 其中在ios播放時卻不行了&#xff0c;查詢官方文檔后發現&#xff0c;ios必…

輕談BFC

BFC 定義 CSS2.1的定義 Block formatting contexts 9.4.1 Block formatting contexts Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and table-captions) that are not block boxes, and block boxes with overflow other …

Java中的Selenium / WebDriver示例

幾年前&#xff0c;我正在忙于一些工作&#xff0c;客戶希望了解如何解決現實世界中的問題。 他們要求我自動化woot.com網站上的某些任務。 他們的任務是訪問各個網站&#xff0c;并閱讀當天商品的名稱和價格。 我寫了一些Selenium代碼&#xff0c;以為可以將其張貼在這里&am…

c語言中怎樣實現空格的替換,C語言實現去除字符串中空格的簡單實例

在網上看了些去除空格的代碼,覺得都不是很簡潔,就自己寫代碼實現它本著高效率,不使用額外存儲空間的想法實現該功能去除空格一共有三種&#xff1a;1、去除全部空格&#xff1b;2、一種是去除左邊空格&#xff1b;3、去除右邊空格想去除左右兩邊空格&#xff0c;只要先去除左邊…

python消息隊列中間件_python-RabbtiMQ消息隊列

1.RabbitMQ簡介AMQP&#xff0c;即Advanced Message Queuing Protocol&#xff0c;高級消息隊列協議&#xff0c;是應用層協議的一個開放標準&#xff0c;為面向消息的中間件設計。消息中間件主要用于組件之間的解耦&#xff0c;消息的發送者無需知道消息使用者的存在&#xff…

CSS position(定位)屬性

關于CSS position&#xff0c;來自MDN的描述&#xff1a; CSS position屬性用于指定一個元素在文檔中的定位方式。top、right、bottom、left 屬性則決定了該元素的最終位置。 然后來看看什么是文檔流(normal flow)&#xff0c;下面是 www.w3.org 的描述&#xff1a; Normal flo…

tomcat配置文件server.xml詳解

版權聲明&#xff1a;本文為博主原創文章&#xff0c;未經博主允許不得轉載。 目錄(?)[] 元素名 屬性 解釋 server port 指定一個端口&#xff0c;這個端口負責監聽關閉tomcat 的請求 shutdown 指定向端口發送的命令字符串 service name 指定service 的名字 Con…

均值,方差,協方差,協方差矩陣,特征值,特征向量

大牛博客&#xff0c;收藏一下 http://blog.csdn.net/yangleo1987/article/details/52845912轉載于:https://www.cnblogs.com/gaohai/p/8086626.html

Java ByteBuffer –速成課程

以我的經驗&#xff0c;當開發人員第一次遇到java.nio.ByteBuffer時&#xff0c;會引起混亂和細微的錯誤&#xff0c;因為如何正確使用它尚不明顯。 在我對API文檔感到滿意之前&#xff0c;需要反復閱讀API文檔和一些經驗以實現一些微妙之處。 這篇文章是關于如何正確使用它們的…

c語言cth三角函數表示,三角函數與雙曲函數基本公式對照表

圓函數(三角函數)1.基本性質&#xff1a;sin tan cos x x x ,cos cot sin xx x 1sec cos x x ,1csc sin x x tan cot 1x x sin csc 1x x sec cos 1x x 22sin cos 1x x 221tan sec x x ,221cot csc x x 2.奇偶性&#xff1a;sin()sin x x -- cos()cos x x - tan()tan x x --3.…

實現編輯功能有哪幾個action_Web 應用的撤銷重做實現

背景前不久&#xff0c;我參與開發了團隊中的一個 web 應用&#xff0c;其中的一個頁面操作如下圖所示&#xff1a;GIF這個制作間頁面有著類似 PPT 的交互&#xff1a;從左側的工具欄中選擇元素放入中間的畫布、在畫布中可以刪除、操作&#xff08;拖動、縮放、旋轉等&#xff…

為什么我們要做三份 Webpack 配置文件

時至今日&#xff0c;Webpack 已經成為前端工程必備的基礎工具之一&#xff0c;不僅被廣泛用于前端工程發布前的打包&#xff0c;還在開發中擔當本地前端資源服務器&#xff08;assets server&#xff09;、模塊熱更新&#xff08;hot module replacement&#xff09;、API Pro…

使用maven插件構建docker鏡像

為什么要用插件 主要還是自動化的考慮&#xff0c;如果額外使用Dockerfile進行鏡像生成&#xff0c;可能會需要自己手動指定jar/war位置&#xff0c;并且打包和生成鏡像間不同步&#xff0c;帶來很多瑣碎的工作。 插件選擇 使用比較多的是spotify的插件:https://github.com/spo…

windows下如何安裝pip以及如何查看pip是否已經安裝成功?

最近剛學習python&#xff0c;發現很多關于安裝以及查看pip是否安裝成的例子都比較老&#xff0c;不太適合于現在&#xff08;python 3.6 &#xff09;因此&#xff0c;下一個入門級別的教程。 0&#xff1a;首先如何安裝python我就不做介紹了。 1&#xff1a;如果安裝的是pyth…

檢查用戶顯示器的分辨率

檢查用戶顯示器的分辨率 轉載于:https://www.cnblogs.com/Renyi-Fan/p/8088012.html

android 字體 dpi,詳解Android開發中常用的 DPI / DP / SP

Android的碎片化已經被噴了好多年&#xff0c;隨著國內手機廠商的崛起&#xff0c;碎片化也越來越嚴重&#xff0c;根據OpenSignal的最新調查&#xff0c;2014年市面上有18796種不同的Android設備&#xff0c;作為開發者&#xff0c;一個無法回避的難題就是需要適配各種各樣奇奇…

android studio閃退代碼不報錯_代碼不報錯,不代表真的沒錯

今天是生信星球陪你的第695天大神一句話&#xff0c;菜鳥跑半年。我不是大神&#xff0c;但我可以縮短你走彎路的半年~就像歌兒唱的那樣&#xff0c;如果你不知道該往哪兒走&#xff0c;就留在這學點生信好不好~這里有豆豆和花花的學習歷程&#xff0c;從新手到進階&#xff0c…

Centos7操作系統部署指南

一、硬件環境&#xff1a; Dell R620 二、軟件環境&#xff1a; Centos6.4 X86_64 KVM Windows7vnc 三、安裝說明 操作系統更新之迅速&#xff0c;讓作為新手的系統運維人員有點措手不及&#xff0c;相對于老手就胸有成竹。怎么講&#xff1f;由于老手對技術方向把握的非常好&…