spring MVC 文件上传简单示例

spring MVC 文件上传简单示例

 

这里使用的是form 表单上传,所以需要设置form的enctype=”multipart/form-data”。

 

uplaodFile.jsp

1 <form id="questionForm" action="<%=request.getContextPath()%>/insertAnswerInfo.action"method="post" enctype="multipart/form-data" >
2 <textarea id="hqcontent" name="answerContent"></textarea>
3 <input type="file" name="file" class="upload"  onchange="Javascript:validate_img(this);">
4 <input id="subBtn" class="btn" type="submit" title="提交"  value="提交"/>
5 </form>

 

图片上传到服务器,数据库里存储的是文件的上传路径,用字段filePath存储。

 

uploadController.java

 1 @Controller
 2 public class uploadController{
 3 
 4     @Autowired
 5     private HdCommunicationService hdCommunicationService;
 6 
 7     @RequestMapping(value = "/insertAnswerInfo")
 8         public ModelAndView insertPersonalAnswer(@RequestParam(value = "file", required = false) MultipartFile file,
 9             HttpServletRequest request, HttpServletResponse response,
10             ModelAndView model) {
11 
12             //String realPath = request.getSession().getServletContext().getRealPath("/upload");
13 
14             String url = " ";
15             try {
16              url = UploadFileUtil.multipartUploadUtil(file,  request);
17             } catch (IOException e) {
18 
19                 e.printStackTrace();
20             } catch (Exception e) {
21 
22                 e.printStackTrace();
23             }
24             String content = request.getParameter("answerContent");
25 
26             HdCommunication communication = new HdCommunication();
27                 communication.setContent(content);
28                 communication.setFilePath(url);
29             hdCommunicationService.insertPersonQuestion(communication);
30 
31             model.setViewName("redirect:/userMain.action?userName="+idcard+"&password="+password);
32 
33             return model;
34 
35         }
36 
37 }

 

工具类:UploadFileUtil.java

 

 1 public class UploadFileUtil {/**
 2      * 
 3      * <b>功能:上传</b><br>
 4      * <br>
 5      * @Author:predestinate
 6      * @param file:要上传的文件
 7      * @param request
 8      * @return 返回上传的路径+文件名,可直接保存到数据库
 9      * @throws Exception
10      * @throws IOException String
11      *
12      */public static String  multipartUploadUtil(MultipartFile file,HttpServletRequest request) throws Exception, IOException {
13 
14         String result = "";
15         //如果参数为空则返回空if(file == null ){
16             return result;
17         }
18 
19         //获取文件名称
20         String filename = file.getOriginalFilename();
21 
22         //获取文件扩展名
23         String extension = FilenameUtils.getExtension(filename);
24 
25         if(filename!=null && !filename.equals("") && extension!=null && !extension.equals("")){
26 
27         //图片名称生成策略:采用时间格式(精确到秒)并追加随机5位(10以内)数字
28         DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
29         String fileDate = df.format(new Date());
30 
31         //年月日时分秒_五位随机数.扩展名
32         String picName = "/upload/"+fileDate+"_"+UploadFileUtil.getFixLenthString(5)+"."+extension;
33         //获取文件上传路径
34         Properties prop = new Properties();
35         InputStream in = UploadFileUtil.class.getResourceAsStream("/resources/uploadFileURL.properties");
36         prop.load(in);
37         String absoluteURL = prop.getProperty("absoluteURL");
38 
39         File targetFile = new File(absoluteURL,picName);
40 
41         // 创建父级目录
42         File p  = targetFile.getParentFile();
43         if(!p.exists()){
44             p.mkdirs();
45         }
46         //如果路径不存在,就创建if(!targetFile.exists()){
47             targetFile.mkdirs();
48         }
49 
50         file.transferTo(targetFile);
51 
52         String basePath = request.getScheme() + "://" + request.getServerName()
53                 + ":" + request.getServerPort();
54 
55         return basePath+absoluteURL+picName;
56         }
57 
58         return result;
59     }
60 
61     /*
62      * 返回长度为【strLength】的随机数,在前面补0
63      */private static String getFixLenthString(int strLength) {
64 
65         Random rm = new Random();
66 
67         // 获得随机数double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);
68 
69         // 将获得的获得随机数转化为字符串
70         String fixLenthString = String.valueOf(pross);
71 
72         // 返回固定的长度的随机数return fixLenthString.substring(1, strLength + 1);
73     }
74 
75 }

 

properties配置文件:resources目录下的uploadFileURL.properties

 

1 absoluteURL=/文件名
2 //例如absoluteURL=abb

 

posted @ 2016-08-16 11:30  年华本纪  阅读(179)  评论(0编辑  收藏  举报