SpringMVC文件上传下载

1. 文件上传

@Controller
public class UploadController {

    @RequestMapping("/upload")
    public String fileUpload(@RequestParam("file") CommonsMultipartFile file,
                             HttpServletRequest request) {
        // 检测是否为多媒体上传
        if (!ServletFileUpload.isMultipartContent(request)) {
            request.setAttribute("msg","非法文件");
            return "forward:/message.jsp";
        }
        //上传文件保存路径
        String path = request.getServletContext().getRealPath("./WEB-INF/upload");
        File fileDir = new File(path);
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }
        //上传文件地址
        System.out.println("上传文件保存地址:"+ fileDir);

        //通过CommonsMultipartFile的方法直接写文件
        try {
            file.transferTo(new File(fileDir + File.separator + file.getOriginalFilename()));
            request.setAttribute("msg","文件上传成功!");
        } catch (IOException e) {
            request.setAttribute("msg","文件上传失败!");
            e.printStackTrace();
        }
        return "forward:/message.jsp";
    }
}

2. 文件下载

@Controller
public class downloadController {

    @RequestMapping("/download/{filename:.+}")
    public void fileUpload(@PathVariable("filename") String filename,
                           HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 1.上传文件保存路径
        String path = request.getServletContext().getRealPath("./WEB-INF/upload");

        // 2.设置响应头
        response.reset();//设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8");//字符编码
        // 3.通知浏览器以下载的方式打开
        response.addHeader("Content-Type", "application/octet-stream");//传输通用二进制文件
        response.addHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
        // 4.通过文件流读取文件
        File file = new File(path, filename);
        FileInputStream fs = new FileInputStream(file);
        // 5.获取response对象的输出流
        ServletOutputStream os = response.getOutputStream();
        // 6.创建缓冲区,文件对拷
        byte[] buffer = new byte[1024];
        int len;
        // 7.循环取出流中的数据
        while ((len = fs.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        //8.关闭流资源
        os.close();
        fs.close();

    }
}

你可能感兴趣的:(IO)