前言
今天使用ssm框架+maven+layui前端框架写一个图片上传。
操作
前端
在这里插入图片描述
在这里插入图片描述
后台
//增加图片
@RequestMapping(value = “/addImage”, method = RequestMethod.POST)
@ResponseBody
public String addDish(MultipartFile file, HttpServletRequest request) throws Exception {
String path = null;// 文件路径
double fileSize = file.getSize();
System.out.println(“文件的大小是”+ fileSize);

    byte[] sizebyte=file.getBytes();
    System.out.println("文件的byte大小是"+ sizebyte.toString());



    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 = "D:/File/image/"+trueFileName;
                System.out.println("存放图片文件的路径:" + path);

                // 转存文件到指定的路径
                file.transferTo(new File(path));
                System.out.println("文件成功上传到指定目录下");

                return "文件成功上传到指定目录下"+path;
            }

        } else {
            System.out.println("不是我们想要的文件类型,请按要求重新上传");
            return "不是我们想要的文件类型,请按要求重新上传";
        }
    } else {
        System.out.println("文件类型为空");
        return "文件类型为空";
    }

    return "已经成功上传到指定目录";
}

配置文件
1、spring-mvc.xml配置文件上传解析器
在这里插入图片描述
2、pom.xml引入两个jar包

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.4</version>
</dependency>
<!-- 文件上传包 -->
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.1</version>
</dependency>
**效果**
![在这里插入图片描述](https://img-blog.csdnimg.cn/20201112234839920.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDA5NjEzMw==,size_16,color_FFFFFF,t_70#pic_center)

总结
以上步骤将图片上传到指定位置,然后返回图片路径,然后可以在写一个接口将图片介绍等其他参数同图片路径一起存到数据库,然后就可以从数据库查询出图片了。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐