ssm框架下的文件上传和文件下载

最近在做一个ssm的项目,遇到了添加附件和下载的功能,在网上查了很多资料,发现很多都不好用,经过摸索,发现了一套简便的方法,和大家分享一下。

1.在自己已经构建好的maven  web项目中 pom.xml配置文件中添加上传下载所需要的jar包

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

2.在spring的applicationContext.xml配置文件中添加文件上传解析器

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
     <property name="defaultEncoding" value="utf-8"></property>    
     <property name="maxUploadSize" value="5242440"></property>    
</bean>

 

3.文件上传
前台页面使用了easyui,代码如下:

<table>
<tr>
<td>附件</td>
<td>
<input class="easyui-filebox" type="file" name="file1" id="file1"><a href="javascript:imageUpload()" class="easyui-linkbutton">上传</a>
</td>
<td>
<input type="hidden"  id="ssFile" name="ssFile"> <!--用于文件名回显-->
</td>
</tr>
</table>

 

JS方法调用后台:

function imageUpload(){
        var file1 = document.getElementById("file1");  
        var ssFile = document.getElementById("ssFile");  
            ssFile.value = file1.value.substring(12);    //取出文件名,并赋值回显到文本框,用于向后台传文件名
        $.ajaxFileUpload({
            url : '${pageContext.request.contextPath}/bug/uploadFile.do', //用于文件上传的服务器端请求地址
            fileElementId : 'file1', //文件上传空间的id属性  <input type="file" id="file" name="file" />
            type : 'post',
            dataType : 'text', //返回值类型 一般设置为json
            success : function(data, status) //服务器成功响应处理函数
            {
                alert("文件上传成功");

            },
            error : function(data, status, e)//服务器响应失败处理函数
            {
                alert("文件上传失败");

            }
        });
    }

  后台实现:

@RequestMapping(value="/uploadFile.do" ,produces="text/html;charset=utf-8" )  
    public @ResponseBody String importPicFile1( 
  @RequestParam MultipartFile file1,HttpServletRequest request){  
                
              Map<String,Object> map= new HashMap<String,Object>();  
               if(file1.isEmpty()){  
                    map.put( "result", "error");  
                    map.put( "msg", "上传文件不能为空" );  
              } else{  
                    String originalFilename=file1.getOriginalFilename();  
                    String fileBaseName=FilenameUtils.getBaseName(originalFilename); 
                    Date now = new Date();
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
                    String floderName=fileBaseName+"_" +df.format(now);  
                     try{   
                           //创建要上传的路径
                         File fdir = new File("D:/file");
                         if (!fdir.exists()) { 
                             fdir.mkdirs(); 
                             }
              //文件上传到路径下
                          FileUtils. copyInputStreamToFile(file1.getInputStream(), new File(fdir,originalFilename));  
                           //coding  
                          map.put( "result", "success");  
                            
                    } catch (Exception e) {  
                          map.put( "result", "error");  
                          map.put( "msg",e.getMessage());  
                            
                    }  
              }  

4.文件下载

前台页面:

<table>
<tr>
<td>附件</td>
<td><a href="" id="ssUrl" class="easyui-linkbutton">下载</a>
</td>
</tr>
</table>

JS方法:

$("#ssUrl").attr('href',"${pageContext.request.contextPath}/bug/download?filename="+fileName) //将后台的路径和文件名赋值给a标签 fileName需要自己从数据库中查出 

后台方法:

/**
     * 文件下载
     * @throws IOException 
     */
    @RequestMapping(value="/download",method=RequestMethod.GET)
    public void download(@RequestParam(value="filename")String filename,
            HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        //模拟文件,myfile.txt为需要下载的文件  
        String path = "D:\\file"+"\\"+filename;  
        //获取输入流  
        InputStream bis = new BufferedInputStream(new FileInputStream(new File(path)));
        //转码,免得文件名中文乱码  
        filename = URLEncoder.encode(filename,"UTF-8");  
        //设置文件下载头  
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);    
        //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型    
        response.setContentType("multipart/form-data");   
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());  
        int len = 0;  
        while((len = bis.read()) != -1){  
            out.write(len);  
            out.flush();  
        }  
        out.close();  
    }

  本人亲测可用,大家有什么意见可以交流,第一次写博客,如有疏漏,请多多指教!

posted @ 2018-04-26 10:21  泡沫同学  阅读(21847)  评论(3编辑  收藏  举报