文件的上传和下载

Posted strugglecola

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了文件的上传和下载相关的知识,希望对你有一定的参考价值。

SpringMVC实现单文件上传

@RequestMapping("/uploadFile")
    public String upload(@RequestParam(value="file") MultipartFile file,
            HttpServletRequest request) throws IllegalStateException, IOException{
        //如果文件不为空,写入上传路径
        if(!file.isEmpty()) {
            //上传文件绝对路径
            String path = request.getServletContext().getRealPath("/images/");
            //上传文件名
            String filename = file.getOriginalFilename();
            File filepath = new File(path,filename);
            //判断路径是否存在,如果不存在就创建一个
            if (!filepath.getParentFile().exists()) { 
                filepath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件当中
            file.transferTo(new File(path + File.separator + filename));
            String showPath = request.getContextPath()+"/images/"+filename;
            
            request.setAttribute("showPath", showPath);
            return "hello";
        } else {
            return "error";
        }
                
                
        
    }

SpringMVC单文件下载

 

以上是关于文件的上传和下载的主要内容,如果未能解决你的问题,请参考以下文章