zoukankan      html  css  js  c++  java
  • SpringMvc的上传和下载

    第一步:配置文件加入上传和下载的<bean>全部配置文件参考上上篇博文

    1 <!-- 配置springMVC上传文件和下载文件 -->
    2     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    3         <property name="defaultEncoding" value="utf-8"></property><!-- 编码格式,与jsp格式一致 -->
    4         <property name="maxUploadSize" value="52428880"></property><!-- 文件上传的最大限制 5mb -->
    5         <property name="uploadTempDir" value="upload/temp"></property><!-- 上传文件的临时路径。文件上传后,会自动消失 -->
    6         <property name="maxInMemorySize" value="4096"/> 
    7     </bean>
    View Code

    第二步:WEB-INF/lib下必加入:commons-fileupload.jar与commons-io-1.4.jar二个文件
    第三步:表单属性为: enctype="multipart/form-data"

    单文件上传的Controller中的方法

     1     /**
     2      * SpringMVC的文件上传
     3      * 【1】上传的文件,会自动被绑定到MultipartFile的对象中。该对象的api
     4      *         (1)byte[] getBytes()获取文件数据
     5      *         (2)String getContentType()获取文件的MIME类型,如image/pjpeg,text/plain等
     6      *         (3)InputStream getInputStream()获取文件流
     7      *         (4)Sring getName()获取表单中文件组件的名称
     8      *         (5)String getOriginalFilename()获取上传文件的原名
     9      *         (6)long getSize()获取文件的字节大小,单位为byte
    10      *         (7)boolean isEmpty():是否有上传的文件
    11      *         (8)void transferTo(File dest) 可以使用给文件将上传文件保存到一个目标目录下        
    12     * @Title: uploadMyPictrue 
    13     * @Description: TODO(这里用一句话描述这个方法的作用) 
    14     * @param file 为前台form表单中<input type="file" name="file"/>中的name
    15     * @return
    16     * @return String    返回类型 
    17     * @author 尚晓飞
    18     * @date 2014-10-31 下午2:01:23
    19      */
    20     @RequestMapping("/uploadMyPictrue")
    21     public String  uploadMyPictrue(HttpServletRequest request,@RequestParam("file") MultipartFile file){
    22         System.out.println("StudentController.uploadMyPictrue()");
    23         boolean flag=file.isEmpty();
    24         if(!file.isEmpty()){
    25             String mimesString=file.getContentType();//获取mime类型
    26             System.out.println("MiME:"+mimesString);//MiME:image/jpeg
    27             long size=file.getSize();
    28             System.out.println("size:"+size);//size:89067
    29             String nameString=file.getName();
    30             System.out.println("组件名称:"+nameString);//组件名称:file
    31             String realName=file.getOriginalFilename();
    32             System.out.println("文件原名:"+realName);//文件原名:图片.jpg
    33             
    34             //获取项目跟目录
    35             String path=request.getSession().getServletContext().getRealPath("");
    36             //拼接上传文件的存放目录
    37             path=path+"/uploadfile";
    38             //为上传文件起一个新名字
    39             Integer index=realName.lastIndexOf(".");
    40             String suffix=realName.substring(index);
    41             //获取当前时间戳
    42             long fileNam=System.currentTimeMillis();
    43             String fileNames=fileNam+suffix;//新的完整文件名
    44             String pathString=path+"/"+fileNames;
    45             File file2=new File(pathString);
    46             
    47             if(!file2.exists()){
    48                 file2.mkdir();//不存在就创建文件
    49             }
    50             //将文件上传到项目制定的目录下
    51             
    52             try {
    53                 file.transferTo(file2);
    54             } catch (IllegalStateException e) {
    55                 // TODO Auto-generated catch block
    56                 e.printStackTrace();
    57             } catch (IOException e) {
    58                 // TODO Auto-generated catch block
    59                 e.printStackTrace();
    60             }finally{
    61                 
    62             }
    63             
    64             
    65         }else{
    66             //上传文件为空
    67         }
    68         return "/page/success";
    69     }
    View Code

    多文件上传的controller中的方法

     1     /**
     2      * 多文件上传
     3     * @Title: moreUploadFile 
     4     * @Description: TODO(这里用一句话描述这个方法的作用) 
     5     * @param request
     6     * @param response
     7     * @param errors
     8     * @return
     9     * @return String    返回类型 
    10     * @author 尚晓飞
    11     * @date 2014-10-31 下午3:12:16
    12      */
    13     @RequestMapping("/moreUploadFile")
    14     public String moreUploadFile(HttpServletRequest request,HttpServletResponse response ){
    15         //将请求作用域转换成上传作用域
    16         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; 
    17         //获取封装了多个上传文件的map
    18         Map<String, MultipartFile> fileMap=multipartRequest.getFileMap();
    19         //获取项目根目录
    20         String rootPath=request.getSession().getServletContext().getRealPath("");
    21         //拼接上传目录
    22         rootPath=rootPath+"\uploadfile";
    23         //逐个上传文件
    24         Set<String> set=fileMap.keySet();
    25         for(String name:set){
    26             //该name的值,为前台form表单中<input type="file" name="xxx">中的xxx
    27             MultipartFile file=fileMap.get(name);
    28             String filename=file.getOriginalFilename();
    29             String fileName=file.getName();//获取组件名 此处的值也是xxx的值
    30             File file2=new File(rootPath+"\"+filename);
    31             if(file2.exists()){
    32                 file2.mkdir();
    33             }
    34             try {
    35                 file.transferTo(file2);
    36             } catch (IllegalStateException e) {
    37                 // TODO Auto-generated catch block
    38                 e.printStackTrace();
    39             } catch (IOException e) {
    40                 // TODO Auto-generated catch block
    41                 e.printStackTrace();
    42             }
    43             
    44         }
    45         
    46         
    47         
    48         return "/page/success";
    49     }
    View Code

    文件下载的controller中的方法

     1     /**
     2      * 文件下载
     3     * @Title: downLoadFile 
     4     * @Description: TODO(这里用一句话描述这个方法的作用) 
     5     * @param request
     6     * @param response
     7     * @return void    返回类型 
     8     * @author 尚晓飞
     9     * @date 2014-10-31 下午3:53:16
    10      */
    11     @RequestMapping("/downLoadFile")
    12     public void downLoadFile(String name,HttpServletRequest request,HttpServletResponse response){
    13         //模拟从数据库查处文件的名
    14         String fileName=name;
    15         //拼接文件全路径
    16         String rootPath=request.getSession().getServletContext().getRealPath("\uploadfile")+"\"+name;
    17         //生成文件
    18         File file=new File(rootPath);
    19         long fileLength =file.length();//获取文件的大小  
    20         
    21         //输入流和输出流
    22         BufferedInputStream bis = null;  
    23         BufferedOutputStream bos = null;  
    24         
    25         
    26         try {
    27             //设置下载的参数配置
    28             response.setContentType("text/html;charset=utf-8");  
    29             request.setCharacterEncoding("UTF-8");
    30             response.setContentType("application/x-msdownload;");  
    31             String files= new String(fileName.getBytes("utf-8"), "ISO8859-1");
    32             response.setHeader("Content-disposition", "attachment; filename="+files);  
    33             response.setHeader("Content-Length", String.valueOf(fileLength));  
    34             
    35             //添加输入流
    36             bis=new BufferedInputStream(new FileInputStream(file));
    37             //添加输出流
    38             bos=new BufferedOutputStream(response.getOutputStream());
    39             byte[] buff = new byte[2048];  
    40             int bytesRead;  
    41             while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
    42                 bos.write(buff, 0, bytesRead);  
    43             }      
    44             
    45         } catch (Exception e) {
    46             // TODO Auto-generated catch block
    47             e.printStackTrace();
    48         }finally{
    49             try {
    50                 if(bis!=null){
    51                     bis.close();
    52                 }
    53                 if(bos!=null){
    54                     bos.close();
    55                 }
    56             } catch (IOException e) {
    57                     // TODO Auto-generated catch block
    58                     e.printStackTrace();
    59             }
    60             
    61         }  
    62         
    63         
    64     }
    View Code
  • 相关阅读:
    11-UIKit(Storyboard、View的基本概念、绘制图形、UIBezierPath)
    10-UIKit(UIDatePicker、UIPickerView、UIWebView、Storyboard)
    09-UIKit(UICollectionViewController、UITabBarController)
    ios7 UITableView底线右移
    08-UIKit(UITableTableViewCell、自定义Cell、xcode调试)
    07-UIKit(tableview的编辑模式、accessoryView)
    06-UIKit(tableView数据模型)
    05-UIKit(UITableViewController)
    04-UIKit(UINavigationController、NSAttributeString、UIImageView)
    HDU 4422 采蘑菇的小女孩
  • 原文地址:https://www.cnblogs.com/shangxiaofei/p/4065506.html
Copyright © 2011-2022 走看看