SpringMVC的文件上传下载

文件上传

from表单:
设置enctype

<form th:action="@{/price/uploadWord}" method="post" enctype="multipart/form-data" id="fileForm">

controller


    @RequestMapping(URLMapping.REGIONAL_PRICE_UPLOADWORD)
    public void uploadWord(MultipartFile file,HttpServletRequest request , HttpServletResponse response){
        /**
         * 获取项目路径
         */
        String absolutePath = request.getServletContext().getRealPath("/") ;
        try{
            String destPath = absolutePath+"uploadFiles/" + file.getOriginalFilename() ;
            File uploadFile = new File(destPath) ;
            if(!uploadFile.exists()){
                uploadFile.getParentFile().mkdirs() ;
                uploadFile.createNewFile() ;
            }
            file.transferTo(uploadFile);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

文件下载
controller:

@RequestMapping("/price/download")
    public void downLoadPdf(HttpServletRequest request , HttpServletResponse response){
        String absolutePath = request.getServletContext().getRealPath("/") ;
        //指定要下载的文件
        File sourceFile = new File(absolutePath+"uploadFiles/Thymeleaf.docx") ;
        try {
            OutputStream out = response.getOutputStream() ;
            InputStream in = new FileInputStream(sourceFile)  ;
            //设置response的时候需要在读写文件之前
            //此处设置下载文件为pdf
            response.setContentType("application/pdf;charset=utf-8");
            String docxName = new String(sourceFile.getName().getBytes(),"iso8859-1");
            String fileName = docxName.replaceAll(".docx", ".pdf") ;
            response.setHeader("Content-Disposition",   "attachment;filename="+fileName);
            byte[] data = new byte[(int) sourceFile.length()];
            int temp=0 ;
            while((temp=in.read(data))!=-1){
                out.write(data, 0, temp);
            }
            in.close();
            out.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

你可能感兴趣的:(hello-world)