springMVC上传图片代码

2020-04-23  本文已影响0人  木羽

html代码

<form action="upload.do" method="post" enctype="multipart/form-data">
        <input type="file" name="uploadFile">
        <input type="submit" text="提交" >
</form>

Controller代码

    @RequestMapping("/upload.do")
    public String upload(Model model,HttpSession session, MultipartFile uploadFile)
            throws Exception {
        //获取文件本来名字
        String originalFilename = uploadFile.getOriginalFilename();
        System.out.println(originalFilename);
        //提取名字的扩展名
        String name = originalFilename.substring(originalFilename.lastIndexOf("."));
        //为文件设置随机的文件名
        UUID uuid = UUID.randomUUID();
        //将图片存到tomcat的webapps文件夹下在重新部署后会清空文件
        //String url = session.getServletContext().getRealPath("/images/book")+"/"+uuid+name;
        //使用绝对路径将文件存到项目下,重新部署没有影响,两种方法可自行选择
        String bookImage = "E:/code/Java/online.bookstore.system/WebContent/images/book";
        String url = bookImage+"/"+uuid+name;
        //判断是否获取到文件
        if (uploadFile.getSize() > 0) {
                File realPath = new File(url);
                System.out.println(realPath.getPath());
                //上传文件
                uploadFile.transferTo(realPath);
        }
        //传递数据 可要可不要
        model.addAttribute("url",url);
        return "/test.jsp";
    }
上一篇下一篇

猜你喜欢

热点阅读