Spring MVC 文件上傳下載

本文基于Spring MVC 注解,讓Spring跑起來。

? ? ? ? (1) 導入jar包:ant.jar、commons-fileupload.jar、connom-io.jar。

? ? ? ? (2) 在src/context/dispatcher.xml中添加

    <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver"  p:defaultEncoding="UTF-8" />  

注意,需要在頭部添加內容,添加后如下所示:

    <beans default-lazy-init="true"  xmlns="http://www.springframework.org/schema/beans"  xmlns:p="http://www.springframework.org/schema/p"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:context="http://www.springframework.org/schema/context"  xmlns:mvc="http://www.springframework.org/schema/mvc"  xsi:schemaLocation="    http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    http://www.springframework.org/schema/mvc     http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd     http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context-3.0.xsd">  

(3) 添加工具類FileOperateUtil.java

    /** * * @author geloin * @date 2012-5-5 下午12:05:57 */  package com.geloin.spring.util;  import java.io.BufferedInputStream;  import java.io.BufferedOutputStream;  import java.io.File;  import java.io.FileInputStream;  import java.io.FileOutputStream;  import java.text.SimpleDateFormat;  import java.util.ArrayList;  import java.util.Date;  import java.util.HashMap;  import java.util.Iterator;  import java.util.List;  import java.util.Map;  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletResponse;  import org.apache.tools.zip.ZipEntry;  import org.apache.tools.zip.ZipOutputStream;  import org.springframework.util.FileCopyUtils;  import org.springframework.web.multipart.MultipartFile;  import org.springframework.web.multipart.MultipartHttpServletRequest;  /** *  * @author geloin * @date 2012-5-5 下午12:05:57 */  public class FileOperateUtil {  private static final String REALNAME = "realName";  private static final String STORENAME = "storeName";  private static final String SIZE = "size";  private static final String SUFFIX = "suffix";  private static final String CONTENTTYPE = "contentType";  private static final String CREATETIME = "createTime";  private static final String UPLOADDIR = "uploadDir/";  /** * 將上傳的文件進行重命名 *  * @author geloin * @date 2012-3-29 下午3:39:53 * @param name * @return */  private static String rename(String name) {  Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss")  .format(new Date()));  Long random = (long) (Math.random() * now);  String fileName = now + "" + random;  if (name.indexOf(".") != -1) {  fileName += name.substring(name.lastIndexOf("."));  }  return fileName;  }  /** * 壓縮后的文件名 *  * @author geloin * @date 2012-3-29 下午6:21:32 * @param name * @return */  private static String zipName(String name) {  String prefix = "";  if (name.indexOf(".") != -1) {  prefix = name.substring(0, name.lastIndexOf("."));  } else {  prefix = name;  }  return prefix + ".zip";  }  /** * 上傳文件 *  * @author geloin * @date 2012-5-5 下午12:25:47 * @param request * @param params * @param values * @return * @throws Exception */  public static List<Map<String, Object>> upload(HttpServletRequest request,  String[] params, Map<String, Object[]> values) throws Exception {  List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();  MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;  Map<String, MultipartFile> fileMap = mRequest.getFileMap();  String uploadDir = request.getSession().getServletContext()  .getRealPath("/")  + FileOperateUtil.UPLOADDIR;  File file = new File(uploadDir);  if (!file.exists()) {  file.mkdir();  }  String fileName = null;  int i = 0;  for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet()  .iterator(); it.hasNext(); i++) {  Map.Entry<String, MultipartFile> entry = it.next();  MultipartFile mFile = entry.getValue();  fileName = mFile.getOriginalFilename();  String storeName = rename(fileName);  String noZipName = uploadDir + storeName;  String zipName = zipName(noZipName);  // 上傳成為壓縮文件  ZipOutputStream outputStream = new ZipOutputStream(  new BufferedOutputStream(new FileOutputStream(zipName)));  outputStream.putNextEntry(new ZipEntry(fileName));  outputStream.setEncoding("GBK");  FileCopyUtils.copy(mFile.getInputStream(), outputStream);  Map<String, Object> map = new HashMap<String, Object>();  // 固定參數值對  
                map.put(FileOperateUtil.REALNAME, zipName(fileName));  map.put(FileOperateUtil.STORENAME, zipName(storeName));  map.put(FileOperateUtil.SIZE, new File(zipName).length());  map.put(FileOperateUtil.SUFFIX, "zip");  map.put(FileOperateUtil.CONTENTTYPE, "application/octet-stream");  map.put(FileOperateUtil.CREATETIME, new Date());  // 自定義參數值對  for (String param : params) {  map.put(param, values.get(param)[i]);  }  result.add(map);  }  return result;  }  /** * 下載 *  * @author geloin * @date 2012-5-5 下午12:25:39 * @param request * @param response * @param storeName * @param contentType * @param realName * @throws Exception */  public static void download(HttpServletRequest request,  HttpServletResponse response, String storeName, String contentType,  String realName) throws Exception {  response.setContentType("text/html;charset=UTF-8");  request.setCharacterEncoding("UTF-8");  BufferedInputStream bis = null;  BufferedOutputStream bos = null;  String ctxPath = request.getSession().getServletContext()  .getRealPath("/")  + FileOperateUtil.UPLOADDIR;  String downLoadPath = ctxPath + storeName;  long fileLength = new File(downLoadPath).length();  response.setContentType(contentType);  response.setHeader("Content-disposition", "attachment; filename="  + new String(realName.getBytes("utf-8"), "ISO8859-1"));  response.setHeader("Content-Length", String.valueOf(fileLength));  bis = new BufferedInputStream(new FileInputStream(downLoadPath));  bos = new BufferedOutputStream(response.getOutputStream());  byte[] buff = new byte[2048];  int bytesRead;  while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  bos.write(buff, 0, bytesRead);  }  bis.close();  bos.close();  }  }  

可完全使用而不必改變該類,需要注意的是,該類中設定將上傳后的文件放置在WebContent/uploadDir下。

? ? ? ? (4) 添加FileOperateController.java

    /** * * @author geloin * @date 2012-5-5 上午11:56:35 */  package com.geloin.spring.controller;  import java.util.HashMap;  import java.util.List;  import java.util.Map;  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletResponse;  import org.springframework.stereotype.Controller;  import org.springframework.web.bind.ServletRequestUtils;  import org.springframework.web.bind.annotation.RequestMapping;  import org.springframework.web.servlet.ModelAndView;  import com.geloin.spring.util.FileOperateUtil;  /** *  * @author geloin * @date 2012-5-5 上午11:56:35 */  @Controller  @RequestMapping(value = "background/fileOperate")  public class FileOperateController {  /** * 到上傳文件的位置 *  * @author geloin * @date 2012-3-29 下午4:01:31 * @return */  @RequestMapping(value = "to_upload")  public ModelAndView toUpload() {  return new ModelAndView("background/fileOperate/upload");  }  /** * 上傳文件 *  * @author geloin * @date 2012-3-29 下午4:01:41 * @param request * @return * @throws Exception */  @RequestMapping(value = "upload")  public ModelAndView upload(HttpServletRequest request) throws Exception {  Map<String, Object> map = new HashMap<String, Object>();  // 別名  String[] alaises = ServletRequestUtils.getStringParameters(request,  "alais");  String[] params = new String[] { "alais" };  Map<String, Object[]> values = new HashMap<String, Object[]>();  values.put("alais", alaises);  List<Map<String, Object>> result = FileOperateUtil.upload(request,  params, values);  map.put("result", result);  return new ModelAndView("background/fileOperate/list", map);  }  /** * 下載 *  * @author geloin * @date 2012-3-29 下午5:24:14 * @param attachment * @param request * @param response * @return * @throws Exception */  @RequestMapping(value = "download")  public ModelAndView download(HttpServletRequest request,  HttpServletResponse response) throws Exception {  String storeName = "201205051340364510870879724.zip";  String realName = "Java設計模式.zip";  String contentType = "application/octet-stream";  FileOperateUtil.download(request, response, storeName, contentType,  realName);  return null;  }  }  

下載方法請自行變更,若使用數據庫保存上傳文件的信息時,請參考Spring MVC 整合Mybatis實例。
? ? ? ? (5) 添加fileOperate/upload.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  <!DOCTYPE html  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  <html>  <head>  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />  <title>Insert title here</title>  </head>  <body>  </body>  <form enctype="multipart/form-data"  action="<c:url value="/background/fileOperate/upload.html" />" method="post">  <input type="file" name="file1" /> <input type="text" name="alais" /><br />  <input type="file" name="file2" /> <input type="text" name="alais" /><br />  <input type="file" name="file3" /> <input type="text" name="alais" /><br />  <input type="submit" value="上傳" />  </form>  </html>  

確保enctype的值為multipart/form-data;method的值為post。 ? ? ? ?

(6) 添加fileOperate/list.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  <!DOCTYPE html  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  <html>  <head>  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />  <title>Insert title here</title>  </head>  <body>  <c:forEach items="${result }" var="item">  <c:forEach items="${item }" var="m">  <c:if test="${m.key eq 'realName' }">  ${m.value }  </c:if>  <br />  </c:forEach>  </c:forEach>  </body>  </html>  

(7) 通過http://localhost:8080/spring_test/background/fileOperate /to_upload.html訪問上傳頁面,通過http://localhost:8080/spring_test/background /fileOperate/download.html下載文件

轉載于:https://www.cnblogs.com/plf112233/p/3637905.html

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

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

相關文章

.php y=mp4,PHP輸出MP4視頻流函數

function GetMp4File($file) {$size filesize($file);header(“Content-type: video/mp4”);header(“Accept-Ranges: bytes”);if(isset($_SERVER[‘HTTP_RANGE’])){header(“HTTP/1.1 206 Partial Content”);list($name, $range) explode(“”, $_SERVER[‘HTTP_RANGE’]…

JMeter學習(四)參數化、斷言、集合點

1.參數化 錄制腳本中有登錄操作&#xff0c;需要輸入用戶名和密碼&#xff0c;假如系統不允許相同的用戶名和密碼同時登錄&#xff0c;或者想更好的模擬多個用戶來登錄系統。 這個時候就需要對用戶名和密碼進行參數化&#xff0c;使每個虛擬用戶都使用不同的用戶名和密碼進行訪…

Windows在安裝builtwith時遇到問題

builtwith是一個十分有用的工具&#xff0c;可以用來檢查網站構建的技術類型。但是我在安裝這個包的時候出現了問題百度之后發現是編碼的問題&#xff0c;應將編碼格式設置為gbk具體過程就是&#xff1a;首先要找到Python路徑下的Lib文件夾的mimetypes.py文件。然后在import下面…

php class使用方法,php的類使用方法問題

php的類使用方法&#xff1a;1、類通過class關鍵字來定義&#xff1b;2、訪問對象的時候&#xff0c;屬性名前不要加【$】&#xff1b;3、通過【->】訪問修改類內成員變量&#xff1b;4、函數的返回值通過return來返回。php的類使用方法&#xff1a;1.語法說明和其他語言一樣…

Linux抓包

tcpdump -i eth1 -nn dst host 172.31.0.42 -w /tmp/temp.cap 監聽指定的主機 $ tcpdump -i eth0 -nn host 192.168.1.231 這樣的話&#xff0c;192.168.1.231這臺主機接收到的包和發送的包都會被抓取。 $ tcpdump -i eth0 -nn src host 192.168.1.231 這樣只有192.168.1.231這…

匯編語言中各種聲明

參考鏈接&#xff1a;http://zhidao.baidu.com/link?urlQZiRv_6nAzF1XHOG83SwngS1HoRZXWSP2a0uQEHVDON1rP1a07xlXCiYUXd0ORQP32h_7Nhfd-afCMox8q8McK 本文僅是為了自己學習方便而已&#xff0c;勿噴。 DATAS SEGMENT;定義數據段 BUF0 DB 1;定義一個字節型變量&#xff0c;名…

linux awk數組相關操作介紹

用awk進行文本處理&#xff0c;少不了就是它的數組處理。那么awk數組有那些特點&#xff0c;一般常見運算又會怎么樣呢。我們先看下以下的一些介紹&#xff0c;結合樣例我們會解說下它的不同之處。在 awk 中數組叫做關聯數組(associative arrays)&#xff0c;由于下標記能夠是數…

java求最優解庫,IPOPT在第二次求解時找到最優解

通常當我嘗試使用IPOPT解決問題時&#xff0c;即使問題不可行&#xff0c;IPOPT也會顯示運行過程&#xff0c;例如顯示問題有多少約束以及問題的其他一般信息&#xff0c;但這次我遇到了一個奇怪的問題 . 我第一次解決它沒有顯示的問題&#xff0c;但第二次解決它&#xff0c;I…

ODAC(V9.5.15) 學習筆記(四)TCustomDADataSet(2)

2.連接相關 名稱 類型 說明 Connection 指向一個數據庫連接對象 Disconnected 設置為True將在數據庫關閉后繼續保持數據集的開啟狀態。 3. 數據獲取 名稱 類型 說明 FetchRows Integer 從數據庫服務器獲取一次性獲取數據記錄的條數&#xff0c;缺省25條。 Is…

詳解匯編語言中乘法指令:MUL、IMUL

本文參考了馬維華老師的《微機原理與接口技術》一書 指令格式&#xff1a; MUL REG/MEM &#xff1b;REG寄存器&#xff0c;MEM存儲器 IMUL REG/MEM MUL和IMUL指令分別用于實現無符號數的乘法和有符號數的乘法運算。都只有一個源操作數&#xff0c;可以使寄存器或存儲…

Android Resource介紹和使用

1. 相關文件夾介紹 在Android項目文件夾里面&#xff0c;主要的資源文件是放在res文件夾里面的。assets文件夾是存放不進行編譯加工的原生文件&#xff0c;即該文件夾里面的文件不會像xml&#xff0c;java文件被預編譯&#xff0c;可以存放一些圖片&#xff0c;html&#xff0c…

mysql.sock 111,錯誤2002(HY000):無法通過套接字’/var/run/mysqld/mysqld.sock’連接到本地MySQL服務器(111)...

在Ubuntu計算機上獲取關于問題“ mysql”命令的錯誤&#xff1a;錯誤2002(HY000)&#xff1a;無法通過套接字’/var/run/mysqld/mysqld.sock’連接到本地MySQL服務器(111)服務未以以下錯誤啟動&#xff1a;rootbettorssidekick:/# service mysql startstart: Job failed to sta…

c語言中的break和continue

break和continue是C語言中的兩條語句&#xff0c;這兩條語句在循環和選擇結構中經常會遇到。 break首先最長見與switch語句中。比如我們設計一個程序&#xff0c;通過輸入學生的成績來確定學生成績等級&#xff0c;等級一共分為四等&#xff0c;分別是優秀、良好、一般、較差&a…

構建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后臺管理系統(44)-工作流設計-設計表單...

構建ASP.NET MVC4EF5EasyUIUnity2.x注入的后臺管理系統&#xff08;44&#xff09;-工作流設計-設計表單 原文:構建ASP.NET MVC4EF5EasyUIUnity2.x注入的后臺管理系統&#xff08;44&#xff09;-工作流設計-設計表單系列目錄 設計表單是比較復雜的一步&#xff0c;完成一個表單…

匯編語言中變量的聲明

參考鏈接為&#xff1a;http://zhidao.baidu.com/link?urlQZiRv_6nAzF1XHOG83SwngS1HoRZXWSP2a0uQEHVDON1rP1a07xlXCiYUXd0ORQP32h_7Nhfd-afCMox8q8McKDATAS SEGMENT;定義數據段BUF0 DB 1;定義一個字節型變量&#xff0c;名稱是BUF0&#xff0c;初始值是01HBUF1 DB "2&qu…

php標簽嵌入規范,HTML標簽嵌套的詳細規則

這次給大家帶來HTML標簽嵌套的詳細規則&#xff0c;HTML標簽嵌套的注意事項有哪些&#xff0c;下面就是實戰案例&#xff0c;一起來看一下。最近在重新學習HTML的知識&#xff0c;算是對HTML的一個重新認識吧&#xff01;別小看了這東西&#xff0c;一切的網頁可都是以它為基礎…

6、動態方法調用和使用通配符定義

action名稱后面:!方法名即可;使用通配符:12345678910111213<?xml version"1.0" encoding"UTF-8" ?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN""http://struts.apache.org/dtds…

Sql 函數大全 (更新中...由難到簡

1.字符處理類&#xff1a; 1.1 指定指定字符輸出的次數 select replicate(1a,5) 結果&#xff1a;1a1a1a1a1a &#xff08;5個1a&#xff09;轉載于:https://www.cnblogs.com/shengwei/p/4479662.html

C錯誤處理

本文為個人學習筆記&#xff0c;僅用于個人學習、復習使用&#xff01;c語言不提供對錯誤處理的直接支持&#xff0c;但是作為一種系統編程語言&#xff0c;它以返回值得形式允許您訪問底層數據&#xff0c;在發生錯誤時&#xff0c;大多數的c或Unix函數調用返回1或NULL&#x…

存儲過程——存儲過程與視圖(三)

數據庫視圖&#xff1a;視圖是虛表&#xff0c;是從一個或幾個基本表&#xff08;或視圖&#xff09;中導出的表&#xff0c;在系統的數據字典中僅存放了視圖的定義&#xff0c;不存放視圖對應的數據。 在sql中視圖是基于sql語句的結果集的可視化的表&#xff1b;視圖包含行和列…