SpringMVC上传下载

来源:互联网 发布:ug编程教程入门视频 编辑:程序博客网 时间:2024/06/10 18:08
@Controllerpublic class UploadController {    @RequestMapping(value = "/upload",method = RequestMethod.POST)    public @ResponseBody String upload(MultipartFile file, HttpServletRequest request){        try {            String path=request.getServletContext().getRealPath("/images/");            String filename=file.getOriginalFilename();            File filepath=new File(path,filename);            if(!filepath.getParentFile().exists()){                filepath.getParentFile().mkdirs();            }            System.out.println(path+File.separator+filename);            FileUtils.writeByteArrayToFile(new File(path+File.separator+filename),file.getBytes());            return "ok";        } catch (Exception e) {            e.printStackTrace();            return "wrong";        }    }    @RequestMapping(value="/download")    public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("filename") String filename) throws Exception{        //下载路径        String path=request.getServletContext().getRealPath("/images/");        File file=new File(path+File.separator+filename);        HttpHeaders headers=new HttpHeaders();        //下载显示文件名,解决中文名称乱码问题        String downloadFileName=new String(filename.getBytes("UTF-8"),"iso-8859-1");        //通知浏览器以attachment(下载方式)打开图片        headers.setContentDispositionFormData("attachment",downloadFileName);        //二进制流数据(最常见的文件下载)        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);    }}