spring mvc文件上传小例子
1.jsp页面
<%@page contentType="text/html;charset=UTF-8"%>
<%@page pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/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",
"修改失败,请上传jpg或gif格式的图片!");
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
* @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;
}}