文件上传

  1. 依赖
<!--文件上传-->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.2</version>
    </dependency>
  1. 前端
<form action="" id="upform" enctype="multipart/form-data">
    <input type="file" name="file">
</form>
<button class="upload">上传</button>

<script>

    $(".upload").click(function () {
        $.ajax({
            url:"/upload",
            data:new FormData($("#upform")[0]),
            type:"POST",
            processData:false,
            contentType:false,
            success:function (re) {
                console.log(re);
            }

        });
    });
</script>
  1. 后端
@RequestMapping("/upload")
    @ResponseBody
    public AjaxData upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {

        String realPath = request.getServletContext().getRealPath("Home");
        String filename = file.getOriginalFilename();
        File dir = new File(realPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String uuname = UUID.randomUUID().toString();
        File image = new File(dir, uuname);
        InputStream in = file.getInputStream();
        FileOutputStream out = new FileOutputStream(image);
        int length = -1;
        byte[] buff = new byte[1024];
        while ((length = in.read(buff)) != -1) {
            out.write(buff, 0, length);
        }
        out.close();

        return new AjaxData(1000,"ss",uuname);

    }
  1. localhost:8080/Home/uuname访问图片

文件下载

  1. controller
@RequestMapping("/xxx")
    public ModelAndView xxx(String filename){
        System.out.println("filename = " + filename);
        ModelAndView mv = new ModelAndView();
        filename=filename+".txt";
        System.out.println("filename = " + filename);
        mv.addObject("filename",filename);
        mv.setView(new DownloadView());
        return mv;
    }
  1. ModelAndView
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String filename = (String) model.get("filename");
        // 读取文件
        File file = ResourceUtils.getFile("classpath:files/" + filename);
        filename=new String(filename.getBytes(), StandardCharsets.ISO_8859_1);
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);
        ServletOutputStream out = response.getOutputStream();
        FileCopyUtils.copy(new FileInputStream(file),out);
        out.close();
    }

  1. html(ajax请求不好使)
<a href="http://localhost:8080/xxx?filename=鹅鹅鹅">鹅鹅鹅</a>

posted on 2020-04-13 10:57  天气警报  阅读(73)  评论(0)    收藏  举报