spring mvc文件上传小例子

1.jsp页面

< contentType="text/html;charset=UTF-8"%>
< pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri=">
<%@ taglib prefix="fmt" uri=">
<%@ taglib prefix="form" uri=">

<form action="mycenter/updatecenter" enctype="multipart/form-data" method="post">

         <tr>

   <td class="r_left" id="businessfileSpan">上传证件的扫描件:</td>
   <td>
   <input type="file" name="businessfile" />
   <input type="hidden" name="business_file" value="${account.business_file}" /> <!-- 若为修改则将以的图片路径也带回给action以便删除或覆盖原有文件-->
   <c:if test="${account.business_file != ''}">
   <img src="${account.business_file}"  width="30" height="30" />
   </c:if>
   </td>
  </tr>
         <input type="submit" value="确定"   />
     </form>

2.action方法(spring mvc 全注解)

  @RequestMapping(value = "updatecenter", method = RequestMethod.POST)
 public String updateUserCenter(MultipartHttpServletRequest request,
   Account account, Model model) { //注这里用的是MultipartHttpServletRequest
      // 获得上传证件的扫描件
  MultipartFile businessFile = request.getFile("businessfile");
  String flag = null;
  if (null != businessFile && 0 != businessFile.getSize()) {//判断是不是空
                       
/**
*saveCenterFile为上传文件自己写的个工具类,主要完成文件上传,并返回上传后的文件完整路径
*参数需要说明的是:(1)account.getBusiness_file(),为上次文件完整路径(修改文件时使用的)
*                  (2)account是新文件将要保存的文件夹拼接
*
**/
   flag = FileUtil.saveCenterFile(request.getSession()
     .getServletContext().getRealPath(""), businessFile,
     account.getBusiness_file(),"account");
   if (flag == "false") {
    model.addAttribute("resultmsg",
      "<font color='red'>修改失败,请上传jpg或gif格式的图片!</font>");
    return "mycenter/resource_user";
   } else {
    account.setBusiness_file(flag); //若上传成功,则将新文件完整路径保持在model中,以便持久话到数据库
   }
  }
      return "redirect:/mycenter/interaccount/resource_user?result=yes";
 }

3.上传工具类

package com.dsg.cccs.utils;

import java.io.File;

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.web.multipart.MultipartFile;

/**

 * @ClassName: FileUtil
 * @Description: TODO
 * @author proteus modoucc_gmail_com
 * @date 2011-8-5 下午5:10:31
 *
 */
public class FileUtil {

 /**

  *
  * @method: saveFile
  * @author: Matty.Cong(Modoucc<AT>gmail.com)
  * @description: TODO
  * @date: 2012-9-16
  * @param fileRealPath
  *            文件实际保存目录
  * @param fileHttpPath
  *            文件HTTP访问目录
  * @param prefix
  *            文件保存的前缀
  * @param uploadFile
  * @return
  */
 public static String saveFile(HttpSession session, String prefix,
   MultipartFile uploadFile) {

  String fileFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());

  /* 文件存储在容器中的实际路径 */

  String saveFilePath = session.getServletContext().getRealPath("/")
    + "/" + prefix + fileFolder + "/";

  /* 构建文件目录 */

  File fileDir = new File(saveFilePath);
  if (!fileDir.exists()) {
   fileDir.mkdirs();
  }

  /* 获取上传的文件名称 */

  String fileNameLong = uploadFile.getOriginalFilename();
  /* 获取文件扩展名 */
  String extensionName = fileNameLong.substring(fileNameLong
    .lastIndexOf(".") + 1);
  /* 重命名文件 */
  String filename = UUID.randomUUID().toString();
  try {
   FileOutputStream out = new FileOutputStream(saveFilePath + filename
     + "." + extensionName);
   out.write(uploadFile.getBytes()); // 写入文件
   out.close();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return prefix +fileFolder+"/"+ filename + "." + extensionName;
 }

 public static String saveFile(String fileRealPath, MultipartFile uploadFile) {

  String baseDir = "/upload/account/";
  String fileFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());
  /* 文件存储的相对路径 */
  String saveDirPath = baseDir + fileFolder + "/";
  /* 文件存储在容器中的绝对路径 */
  // String saveFilePath
  // =request.getSession().getServletContext().getRealPath(saveDirPath)+"/";
  String saveFilePath = fileRealPath + saveDirPath;
  System.out.println(saveFilePath);
  /* 构建文件目录以及目录文件 */
  File fileDir = new File(saveFilePath);
  if (!fileDir.exists()) {
   fileDir.mkdirs();
  }

  /* 获取上传的文件名称 */

  String fileNameLong = uploadFile.getOriginalFilename();
  /* 获取文件扩展名 */
  String extensionName = fileNameLong.substring(fileNameLong
    .lastIndexOf(".") + 1);
  /* 重命名文件 */
  String filename = UUID.randomUUID().toString();
  try {
   FileOutputStream out = new FileOutputStream(saveFilePath + filename
     + "." + extensionName);
   out.write(uploadFile.getBytes()); // 写入文件
   out.close();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return saveDirPath + filename + "." + extensionName;
 }

 public static String updateUserImage(String fileRealPath,

   MultipartFile uploadFile, String filename) {
  String baseDir = "/upload/portImages/";
  /* 文件存储的相对路径 */
  String saveDirPath = baseDir + "/";
  /* 文件存储在容器中的绝对路径 */
  String saveFilePath = fileRealPath + saveDirPath;
  System.out.println(saveFilePath);
  /* 构建文件目录以及目录文件 */
  File fileDir = new File(saveFilePath);
  if (!fileDir.exists()) {
   fileDir.mkdirs();
  }
  /* 获取上传的文件名称 */
  String fileNameLong = uploadFile.getOriginalFilename();

  /* 获取文件扩展名 */

  String extensionName = fileNameLong.substring(fileNameLong
    .lastIndexOf(".") + 1);
  if (!extensionName.equals("jpg")) {
   if (!extensionName.equals("gif")) {
    return "false";
   }
  }
  try {
   FileOutputStream out = new FileOutputStream(saveFilePath + filename
     + "." + extensionName);
   out.write(uploadFile.getBytes()); // 写入文件
   out.close();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return filename + "." + extensionName;
 }

 /**

  * 个人中心上传注册附件,友情连接上传附件 若是修改,则将以前的文件删除
  *
  * @param fileRealPath
  * @param uploadFile
  * @param oldImageUrl
  * @param fileurl
  * @return
  */
 public static String saveCenterFile(String fileRealPath,
   MultipartFile uploadFile, String oldImageUrl, String fileurl) {

  String flag = "";

  try {
   if (null != oldImageUrl && oldImageUrl.length() > 5) {// 这里大于5只是为了防止“”
    File fileDir = new File(fileRealPath + oldImageUrl);
    if (fileDir.exists()) {
     fileDir.delete();
    }
   }
   // 文件存储的相对路径
   String saveDirPath = "/upload/" + fileurl + "/"
     + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/";
   String saveFilePath = fileRealPath + saveDirPath;
   // 构建文件目录以及目录文件
   File fileDir = new File(saveFilePath);
   if (!fileDir.exists()) {
    fileDir.mkdirs();
   }
   // 获取上传的文件名称
   String fileNameLong = uploadFile.getOriginalFilename();
   // 获取文件扩展名
   String extensionName = fileNameLong.substring(fileNameLong
     .lastIndexOf(".") + 1);
   if (!extensionName.equals("jpg")) {
    if (!extensionName.equals("gif")) {
     return "false";
    }
   }
   // 重命名文件
   String filename = UUID.randomUUID().toString();
   FileOutputStream out = new FileOutputStream(saveFilePath + filename
     + "." + extensionName);
   out.write(uploadFile.getBytes()); // 写入文件
   out.close();
   flag = saveDirPath + filename + "." + extensionName;

  } catch (Exception e) {

   e.printStackTrace();
  }
  return flag;
 }}