springMVC文件上傳和下載功能

以下功能框架用的是SSM

備註:上傳成功或出錯我沒有加跳轉界面,大家可以自己加一下,我一般debugger一下,然後看上傳的路徑下有沒有我傳的文件(圖片等格式都可以)

  1.  首先要導入jar包 

<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>${commons-io.version}</version>
</dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>${commons-fileupload.version}</version>
</dependency>

  2.  配置上傳文件默認大小值(springMVC.xml)

 <!-- 配置文件上傳,如果沒有使用文件上傳可以不用配置,當然如果不配,那麼配置文件中也不必引入上傳組件包 -->  
    <bean id="multipartResolver"    
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
        <!-- 默認編碼 -->  
        <property name="defaultEncoding" value="utf-8" />    
        <!-- 文件大小最大值 -->  
        <property name="maxUploadSize" value="10485760000" />    
        <!-- 內存中的最大值 -->  
        <property name="maxInMemorySize" value="40960" />    
    </bean>

   

  3.  jsp界面配置,使用form表單提交,注意設置 enctype="multipart/form-data",如下:

   <form action="fileUpload" method="post" enctype="multipart/form-data">
                    選擇文件:<input type ="file" name="filename">
                                     <input type="submit" value="提交">
               </form>
               <form action="downLoad" method="get">
                        <input type="submit" value="下載">
               </form>

   4.  通過註解方式到Controller,詳見代碼(裏面有一些是自己測試的,不過代碼保證複製可以跑的通,文件路徑等設置成你要下載的或上傳的本地路徑)

  /**
     * 上傳文件到本地(包括壓縮文件)
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
    public DataLib uploadHomework( MultipartFile file,String fileUrl,String dataLibId) {
        if(StringUtils.isNotBlank(fileUrl) && StringUtils.isNotBlank(dataLibId)){
            //刪除表記錄
            dataLibService.deleteDataLibById(dataLibId);
            //編輯或者再次上傳文件,應先刪除文件,再添加
            File url = new File(fileUrl);
            url.delete();
        }
        File saveZipDirectory =null;
        String newName ="";
        String fileName ="";
        DataLib entity = new DataLib();
        try {
            if (!file.isEmpty()) {
                 fileName = file.getOriginalFilename();
                String suffix =  fileName.substring(fileName.lastIndexOf(".")+1);
                    saveZipDirectory = new File(Global.getConfig(uploadFileUrl));//上傳文件真實路徑,靜態文件配置,讀取
                    if (!saveZipDirectory.exists()) {
                        saveZipDirectory.mkdirs();
                    }
                    System.out.println("saveZipDirectory*****Path:" + saveZipDirectory.getAbsolutePath());
                    // 將上傳文件保存到目標文件中
                    //定義文件名 uuid
                     newName = getName(fileName);
                    File toFile = new File(saveZipDirectory.getAbsolutePath() + File.separator + newName);
//                    FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(toFile));
                    file.transferTo(toFile);
            }
        } catch (Exception e) {
            entity.setMsg("上傳失敗");
         return entity;
        }
        // 保存上傳文件,記錄表
        entity.setId(newName.substring(0,newName.lastIndexOf(".")));
        entity.setCreateUserId(UserUtils.getUser().getId());
        entity.setCreateDate(new Date());
        entity.setAddress((saveZipDirectory.getAbsolutePath() + File.separator + newName).replace("\\", "/"));
        entity.setName(fileName);
        entity.setSize(file.getSize()+"");
        entity.setFileType(file.getContentType());
        entity.setFshIpPort("");
        entity.setFileGroup("");
        entity.setFilePath(newName);
        dataLibSer.insertDataLib(entity);
      entity.setMsg("上傳成功");
        return entity;
    }

    /**
     * 下載文件
     * @param request
     * @param response
     */
    @RequestMapping("/downLoad")
    public void downLoad(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            String fileUrl = request.getParameter("fileUrl");
            String url="";
            if(fileUrl!=null&&!"".equals(fileUrl)){
                //message=URLDecoder.decode(imgUrl, "utf-8");
                //修改中文地址亂碼問題
                url= new String(fileUrl.getBytes("ISO8859-1"),"UTF-8") ;

            }
            File file = new File(url);
            String fileName = file.getName();
            if (file != null && fileName != null && fileName.trim() != "") {
                try {
                    InputStream fis = new FileInputStream(file);// 讀取文件流
                    byte[] buffer = new byte[1024 * 8];// 緩衝池
                    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
                    response.reset();
                    // 設置頭信息
                    response.setHeader("Content-Type", "application/x-download");
                    response.addHeader("Content-Disposition","attachment;filename*=utf-8''" + fileName);
                    response.setContentType("application/octet-stream");
                    // 輸出數據
                    OutputStream out = new BufferedOutputStream(response.getOutputStream());
                    int bytes;
                    while ((bytes = fis.read(buffer, 0, buffer.length)) != -1) {
                        out.write(buffer, 0, bytes);
                    }
                    out.close();
                    fis.close();
                } catch (FileNotFoundException e) {
                    throw new Exception("文件未找到!");
                } catch (IOException e) {
                    throw new Exception("取消下載或文件讀寫異常!");
                }

            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}
/**
 * 上傳文件名字變換
 */
public String getName(String myFileName) {
    String newName = IdGen.uuid() + myFileName.substring(myFileName.lastIndexOf("."));
    return newName;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章