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();  
    }

  本人親測可用,大家有什么意見可以交流,第一次寫博客,如有疏漏,請多多指教!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM