Spring boot 上传图片

网友投稿 498 2022-10-11

Spring boot 上传图片

Spring boot 上传图片

@ResponseBody @RequestMapping(path = "/save_photo", method={RequestMethod.POST}) public void addDish(@RequestParam("photos") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception { String path = null;// 文件路径 String json = ""; if (file!=null) {// 判断上传的文件是否为空 String type = null;// 文件类型 String fileName = file.getOriginalFilename();// 文件原名称 System.out.println("上传的文件原名称:"+fileName); // 判断文件类型 type = fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null; if (type!=null) {// 判断文件类型是否为空 if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())) { // 项目在容器中实际发布运行的根路径 String realPath = request.getSession().getServletContext().getRealPath("/"); // 自定义的文件名称 String trueFileName = String.valueOf(System.currentTimeMillis()) + "." + type; // 设置存放图片文件的路径 path = realPath+/*System.getProperty("file.separator")+*/trueFileName; System.out.println("存放图片文件的路径:"+path); // 转存文件到指定的路径 file.transferTo(new File(path)); System.out.println("文件成功上传到指定目录下"); } json = "{\"res\":1}"; }else { System.out.println("不是我们想要的文件类型,请按要求重新上传"); //return null; json = "{\"res\":0}"; } }else { System.out.println("文件类型为空"); //return null; json = "{\"res\":0}"; } }else { System.out.println("没有找到相对应的文件"); json = "{\"res\":0}"; //return null; } response.setContentType("application/json;charset=UTF-8"); response.getWriter().print(json); }

首先注意的是参数要加

@RequestParam("photos") MultipartFile file

你的html可能就类似这样的


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:CharmPy- 分布式并行编程框架(charmp英文怎么读)
下一篇:Spring Boot统一接口返回及全局异常处理
相关文章

 发表评论

暂时没有评论,来抢沙发吧~