SpringMVC---实现文件上传与下载

摘要: 在项目中涉及图片上传的时候 我们往往不会把图片直接以二进制的方式存进数据库,往往是把上传的图片保存在服务器中 ,数据库只存图片在服务器中的路径。如果图片量过多的话 还可以在开一台图片服务器这里可以提高用户的体验。

首先来看文件上传:

一:SpringMVC关于上传文件的配置:

  1. <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 ,其中multipartResolver名称是固定的,它和后台DispatcherServlet中的常量保持一致-->   
  2.     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">   
  3.         <!-- 指定所上传文件的总大小不能超过200000KB。是所有文件的容量之和 -->   
  4.         <property name="maxUploadSize" value="200000000"/>   
  5.     </bean>   
  6.       
  7.     <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 ,可选-->   
  8.     <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">   
  9.         <property name="exceptionMappings">   
  10.             <props>   
  11. <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error/error.jsp>   
  12.                 <prop key="org.springframework.web.multipart.MaxUploadSizeExceededExcep                         tion">error/error</prop>   
  13.             </props>   
  14.         </property>   
  15.     </bean>  

二:创建一个.properties配置文件,例如:src目录下application.properties,该文件主要用于获取服务器图片存放的路径。例如:imagePath=D:/anzhuang/tomcat/apache-tomcat-7.0.67/webapps/image即在服务器下的image  文件夹中存储图片。

三:前端jsp页面

     <form action="upload/doFirst.action" method="post" enctype="multipart/form-data">
<h2>文件上传</h2>
文件:<input type="file" name="uploadFile"/><br/><br/>
<input type="submit" value="提交"/>
</form>

  其中enctype="multipart/form-data"

四:后台页面接收,处理:

        @Controller
@RequestMapping("/upload")
public class UploadAction {
@Autowired
private UploadService uploadService;

@RequestMapping("/doFirst")
public String doFirst(@RequestParam MultipartFile  uploadFile,HttpSession session){

      //其中参数必须有MultipartFile参数进行接收传过来的文件 ,uploadFile则要与前端页面的name属            性uploadFile一致,否则接收不到其次,如果要接收多个文件则需要 MultipartFile[] myfiles来接收。
try {
int cid = 1006;

//获取文件名保存到服务器的文件名称
String fileName = uploadFile.getOriginalFilename();
//在application.properties文件中,要写绝对路径,imagePath=/home/upload/  意味着会直接找到项目所在的盘符下面加入/home/upload目录
//根据配置文件获取服务器图片存放路径
String dir = new ApplicationConfigUtil().getBaseImagePath();
//获得图片的扩展名
String extensionName = fileName.substring(fileName.lastIndexOf(".")+1);
//新的文件名 = 获取时间戳+"."+图片扩展名
String newFileName = String.valueOf(System.currentTimeMillis())+"."+extensionName;
//构建文件目录
File fileDir = new File(dir);
if(!fileDir.exists()){
fileDir.mkdirs();
}
/*方法一:使用transferTo()方法实现:第二种则用流的形式
                       fileDir = new File(fileDir.getAbsolutePath()+"/"+newFileName);
               uploadFile.transferTo(fileDir);*/
String path = dir+"\\"+newFileName;
FileOutputStream out = new FileOutputStream(path);
out.write(uploadFile.getBytes());
out.flush();
out.close();
//将路径保存到数据库
int flag = uploadService.insertImg(path, cid);
} catch (Exception e) {
e.printStackTrace();
System.out.println("出现异常插入失败");
}
return "welcome";
}
}

其次,来看SpringMVC实现文件下载:

  1. @Component  
  2. @Scope("prototype")   
  3. @RequestMapping("/downloadFile")  
  4. public class DownloadAction  
  5. {  
  6.   
  7.     @RequestMapping("download")    
  8.     public ResponseEntity<byte[]> download() throws IOException {    
  9.         String path="D:\\workspace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\springMVC\\WEB-INF\\upload\\图片10(定价后).xlsx";  
  10.         File file=new File(path);  
  11.         HttpHeaders headers = new HttpHeaders();    
  12.         String fileName=new String("你好.xlsx".getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题  
  13.         headers.setContentDispositionFormData("attachment", fileName);   
  14.         headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   
  15.         return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
  16.                                           headers, HttpStatus.CREATED);    
  17.     }    
  18. }  

在浏览器里面写一句,便可以下载文件

[html]  view plain   copy
  在CODE上查看代码片 派生到我的代码片
  1. <a href="./downloadFile/download" >下载</a>  

猜你喜欢

转载自blog.csdn.net/happyAliceYu/article/details/64444887