SSM框架实现文件上传功能

560 阅读1分钟

1、uploadDemo.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传示例</title>
</head>
<body>
<form action="addUserInfo.html" method="post" enctype="multipart/form-data">
用户昵称:<input type="text" name="userName" /><br/>
上传头像:<input type="file" name="userPic"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>

2、UploadController控制器

package com.BooksSys.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传控制器
 * @author Administrator
 *
 */
@Controller
public class UploadController {
	//单个文件的最大值
	private final int FILE_MaxSize=500000;
	
	//1、新增用户资料
	@RequestMapping(value="/addUserInfo.html",method=RequestMethod.POST)
	public String addUserInfo(
			String userName,
			HttpServletRequest request,//通过HttpServletRequest获取文件的保存路径
			Model model,
			@RequestParam(required=false)MultipartFile userPic//@RequestParam(required=false)表示可以不上传文件	
			){
		//(1)、判断上传的文件是否为空
		if(!userPic.isEmpty()){
			//(2)、获取文件的保存路径
			String path= request.getServletContext().getRealPath("statics"+File.separator+"upload");
				//把上传的文件保存在statics/images目录下,File.upload相当于/斜杠				

			System.out.println("文件的保存路径:"+path);
			//(3)、重命名上传的文件(保证 每个上传的文件名称都不一样,以免覆盖,导致资料丢失)
				//先获取旧文件的名称
				String oldFileName=userPic.getOriginalFilename();
				//再获取旧文件的后缀
				String oldFileSuffix=FilenameUtils.getExtension(oldFileName);
				//最后用【时间毫秒数+下划线+哈希值+后缀】生成新的文件名
				String newFileName=System.currentTimeMillis()+"_"+oldFileName.hashCode()+"."+oldFileSuffix;
				//String dateStrig=new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());
				//String newFileName=dateStrig+oldFileName.hashCode()+"."+oldFileSuffix;								

			//4、限制上传文件的大小
			if(userPic.getSize()>FILE_MaxSize){
				model.addAttribute("error", "上传的文件大小不得超过500KB");
				return "uploadResult";//转发到uploadResult.jsp页面
			}
			//5、限制上传文件的类型
			if(!oldFileSuffix.equalsIgnoreCase("gif")){
				model.addAttribute("error", "文件格式必须为gif");
				return "uploadResult";//转发到uploadResult.jsp页面
			}			
			//6、生成新文件
			File newPic=new File(path, newFileName);
			  //新建用于保存上传文件的文件夹
			  if(!newPic.exists()){
				  newPic.mkdirs();//如果不存在,就创建文件夹
			  }
			  
			//7、将旧文件内容保存到新文件里
			try {
				userPic.transferTo(newPic);		
				model.addAttribute("info", "上传成功");
				//保存文件名
				model.addAttribute("pic", newFileName);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				model.addAttribute("info", "上传失败");
			}
		}
		return "uploadResult";//转发到uploadResult.jsp页面
	}
}


\