SpringMVC 使用总结

来源:互联网 发布:hex文件转换成c语言 编辑:程序博客网 时间:2024/05/29 14:39

SpringMVC下载文件的方法

注释部分是常规下载方法

    private ResponseEntity<byte[]> download(String path, HttpServletResponse response) {          try {              // path是指下载的文件的路径。              File file = new File(path);              // 取得文件名。              String filename = file.getName();              // 以流的形式下载文件。  //            InputStream fis = new BufferedInputStream(new FileInputStream(path));  //            byte[] buffer = new byte[fis.available()];  //            fis.read(buffer);  //            fis.close();  //            //            // 清空response  //            response.reset();  //            // 设置response的Header  //            response.addHeader("Content-Disposition", "attachment;filename="+ new String(filename).getBytes());  //            response.addHeader("Content-Length", "" + file.length());  //            response.setContentType("application/vnd.ms-excel;charset=utf-8");  //            //            OutputStream bos = new BufferedOutputStream(response.getOutputStream());  //            bos.write(buffer);//            //            bos.flush();  //            bos.close();             String dfileName = new String(filename.getBytes("utf-8"),"iso-8859-1");            HttpHeaders headers = new HttpHeaders();            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);            headers.setContentDispositionFormData("attachment", dfileName);            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);        } catch (IOException ex) {              ex.printStackTrace();          }        return null;    }  

SpringMVC文件上传的方法

@RequestMapping(value = "/saveAdInfo", method = RequestMethod.POST)    public void saveAdInfo(HttpServletRequest request,HttpServletResponse response,AdInfo ai,            String editType,String resKey,@RequestParam("adImage") MultipartFile adImage) throws IllegalStateException, IOException{    String fileName = adImage.getOriginalFilename();    File targetDir = new File(path + imgPath);        if (!targetDir.exists()) {            targetDir.mkdirs();        }    // 保存    adImage.transferTo( new File(targetDir +"/" + fileName));}
0 0
原创粉丝点击