Spring MVC 系列(五)——Spring MVC上传功能源码

本文介绍如何使用SpringMVC实现文件上传功能,包括引入必要的jar包、编写JSP前端页面及后端处理代码等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用Spring MVC实现上传功能,在项目开发中也是经常使用到的。例如在使用Spring MVC时,上传和Struts也有大部分相似的处理。

如图1所示,首先引入上传相关罐

 com.springsource.org.apache.commons.fileupload-1.2.0.jar

com.springsource.org.apache.commons.io-1.4.0.jar

2,编写前台JSP代码

【JAVA]   查看纯 字幕:  
  1. <BODY>  
  2.    <form action = “test / upload.do”  method = “post”  enctype = “multipart / form-data” >  
  3.     图:<input type = “file”  name = “pic” > <br>  
  4.     <input type = “submit”  value = “submit” > <br>  
  5.    </ FORM>  
  6.  </ BODY>  

3,后台上传代码

【JAVA]   查看纯 字幕:  
  1. @RequestMapping (value = “/upload.do” )  
  2.     public  String upload(Person person,HttpServletRequest request)  throws  Exception {  
  3.         //第一步转化请求  
  4.         MultipartHttpServletRequest rm =(MultipartHttpServletRequest)请求;  
  5.         //获得文件  
  6.         CommonsMultipartFile cfile =(CommonsMultipartFile)rm.getFile(“pic” );  
  7.         //获得文件的字节数组       
  8.         byte [] bfile = cfile.getBytes();  
  9.         String fileName = “”;  
  10.         //获得当前时间的最小精度  
  11.         SimpleDateFormat format =  new SimpleDateFormat(“yyyyMMddHHmmssSSS”);  
  12.         fileName = format.format(new Date());  
  13.         //获得三位随机数  
  14.         随机随机=  随机();  
  15.         forint i = 0; i < 3; i ++){  
  16.             fileName = fileName + random.nextInt(9);  
  17.         }  
  18.         //获得原始文件名  
  19.         String origFileName = cfile.getOriginalFilename();  
  20.         //XXX.jpg  
  21.         字符串后缀= origFileName.substring(origFileName.lastIndexOf(“。”));  
  22.         //拿到项目的部署路径  
  23.         String path = request.getSession()。getServletContext()。getRealPath(“/” );  
  24.         //定义文件的输出流  
  25.         OutputStream out =  new  FileOutputStream(new  File(path + “/ upload /” + fileName + suffix));  
  26.         out.write(BFILE);  
  27.         了了out.flush();  
  28.         out.close();  
  29.         返回“/ index” ;   
  30.     }  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值