springmvc文件下載和上傳

下載模塊:

  @RequestMapping("/download")
    public static void download(HttpServletRequest request,  
              HttpServletResponse response, String storeName, String contentType
               ) throws Exception {  

            request.setCharacterEncoding("UTF-8");  
            BufferedInputStream bis = null;  
            BufferedOutputStream bos = null;  

            //獲取項目根目錄
//          String ctxPath = request.getSession().getServletContext()  
//              .getRealPath("");  

            //獲取下載文件露肩
            String downLoadPath = "F:\\gp\\李霞\\Activity.doc";  

            //獲取文件的長度
            long fileLength = new File(downLoadPath).length();  
            String filename="Activity學習總結.doc";
            //設置文件輸出類型
            response.setContentType("application/octet-stream");  
            response.setHeader("Content-disposition", "attachment; filename="  
                + new String(filename.getBytes("utf-8"), "ISO8859-1")); 
            //設置輸出長度
            response.setHeader("Content-Length", String.valueOf(fileLength));  
            //獲取輸入流
            bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
            //輸出流
            bos = new BufferedOutputStream(response.getOutputStream());  
            byte[] buff = new byte[2048];  
            int bytesRead;  
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
              bos.write(buff, 0, bytesRead);  
            }  
            //關閉流
            bis.close();  
            bos.close();  
          }  

上傳模塊:
前臺頁面參考

https://blog.csdn.net/qq_36345181/article/details/79929650

後臺
Controller層

    @RequestMapping("/file/upload")
    @ResponseBody
    public R doUploadFile(@ModelAttribute GPFile gpFile, String fileName) {

        if (!gpFile.getUploadFile().isEmpty()) {
            try {
                String username = (String) SessionUtiles.getLoginName();
                String filepath = "F:\\gp\\" + username;
                // 這裏將上傳得到的文件保存至目錄
                FileUtils.copyInputStreamToFile(gpFile.getUploadFile().getInputStream(),
                        new File(filepath, gpFile.getUploadFile().getOriginalFilename()));
                // 上傳者的信息
                User user = loginService.findBypwd(username);
                gpFile.setUserId(user.getId());
                gpFile.setFileAddress(filepath);
                commonService.insert(gpFile);
            } catch (IOException e) {
                e.printStackTrace();
                return R.error("上傳失敗");
            }
        }
        return R.ok();
    }

Bean層

public class GPFile implements Serializable
{
    private Long id;

    private String fileName;

    private String fileAddress;

    private String fileType;

    private Long userId;

    private Date gmtCreate;

    private Date gmtModified;

    private MultipartFile uploadFile;

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