SpringMVC框架之处理文件上传(附照片上传Demo)

在上一篇 Spring、SpringMVC、Mybatis框架整合(IDEA)(附Demo) 演示了SSM框架的整合,但是Product照片上传还没有实现,在本篇博客将实现该功能。
本篇博客就不再复述项目创建、配置了,直接去Spring、SpringMVC、Mybatis框架整合(IDEA)(附Demo)下载Demo源码即可。

SpringMVC框架处理文件上传,是对Apache fileupload的封装,由MultipartFile接口来实现文件上传。在Java Web哪块我就写过一篇运行Apache fileupload上传文件的博客 Java Web 通过JSP上传文件实例

1、导入Apache fileupload依赖

commons-io下载地址:https://mvnrepository.com/artifact/commons-io/commons-io/2.6

在这里插入图片描述
commons-fileupload下载地址:https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload/1.4
在这里插入图片描述
在这里插入图片描述

2、导入jQuery js库

在这里插入图片描述

3、配置SpringMVC文件接收器

在这里插入图片描述

<!-- 5.配置springmvc文件处理 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 设置上传图片文件的大小 单位为Byte 5M=1024*1024*5 -->
    <property name="maxUploadSize" value="5242880"/>
</bean>

4、修改add.jsp页面

在这里插入图片描述

<%--
  Created by IntelliJ IDEA.
  User: hestyle
  Date: 2020/1/30
  Time: 11:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加产品</title>
    <script src="${pageContext.request.contextPath}/js/jquery-1.8.3.js"></script>
    <script>
        function upload() {
            //从id=pictureFile的input标签获取选中的文件,然后组成form,提交到uploadPicture.do
            var pictureForm = new FormData();
            pictureForm.append("pictureFile", document.getElementById("pictureFile").files[0]);
            $.ajax({
                "url" : "${pageContext.request.contextPath}/product/uploadPicture.do",
                "data" : pictureForm,
                "type" : "POST",
                "contentType": false,/*上传文件必须要的*/
                "processData": false,/*上传文件必须要的*/
                "dataType" : "json",
                "success" : function (json) {
                    if (json.code === 200) {
                        //如果提交成功,则把返回的上传到服务器图片路径设置到picturePath标签
                        $("input[name='picturePath']").val(json.msg);
                    } else {
                        alert(json.msg);
                        $("input[name='picturePath']").val("");
                    }

                },
                "error" :function () {
                    alert("出错!");
                }
            });
        }
    </script>
</head>
<body>
    <!-- 以post请求方式,发送请求给product/save.do -->
    <form action="${pageContext.request.contextPath}/product/save.do" method="post">
        <table border="1">
            <tr>
                <td>产品名</td>
                <td><input type="text" name="name"></td>
            </tr>
            <tr>
                <td>产品价格</td>
                <td><input type="text" name="price"></td>
            </tr>
            <tr>
                <td>库存数量</td>
                <td><input type="text" name="number"></td>
            </tr>
            <tr>
                <td>产品简介</td>
                <td><textarea name="info"></textarea></td>
            </tr>
            <tr>
                <td>产品照片<input type="text" name="picturePath" value="" hidden></td>
                <!-- 当选择的照片发生了变化,调用upload()方法,上传图片到服务器 -->
                <td><input type="file" id="pictureFile" onchange="upload()" accept=".jpg, .jpeg, .png"></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="添加" align="center"></td>
            </tr>
        </table>
    </form>
</body>
</html>

5、在ProductController中添加uploadPicture方法

在这里插入图片描述

@RequestMapping("uploadPicture.do")
public void uploadPicture(MultipartFile pictureFile, HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setHeader("contentType", "text/json,charset=utf-8");
    // 1、判断文件是否为空,空则返回失败页面
    if (pictureFile.isEmpty()) {
        response.getWriter().write("{\"code\":500,\"msg\":\"文件为空!\"}");
        return;
    }
    // 2、获取文件存储路径(绝对路径)
    String path = request.getServletContext().getRealPath("/picture/product");
    // 获取原文件扩展名
    String[] tempStrings = pictureFile.getOriginalFilename().split("\\.");
    String suffix = tempStrings[tempStrings.length - 1].toLowerCase();
    if (!"png".equals(suffix) && !"jpg".equals(suffix) && !"jpeg".equals(suffix) ) {
        response.getWriter().write("{\"code\":500,\"msg\":\"只允许上传png、jpg、jpeg格式的文件!\"}");
        return;
    }
    String fileName = UUID.randomUUID().toString() + "." + suffix;
    // 3、创建文件实例
    File filePath = new File(path, fileName);
    // 如果文件目录不存在,创建目录
    if (!filePath.getParentFile().exists()) {
        filePath.getParentFile().mkdirs();
    }
    System.err.println("创建文件" + filePath.getAbsolutePath());
    // 4、写入文件
    pictureFile.transferTo(filePath);
    // 5、把文件存放的项目相对路径返回
    response.getWriter().write("{\"code\":200,\"msg\":\"/picture/product/" + fileName + "\"}");
}

6、重新部署项目,访问add.do页面

在这里插入图片描述
在这里插入图片描述
这里涉及到Ajax异步请求、JQuery选择器、文件读写操作,不过都比较基础,主要是看一下配置过程。
Demo源码下载地址:
地址一:https://pan.baidu.com/s/1x_hcPZP12Lwt94ZnbEbNhw 提取码: 3313
地址二:https://pan.baidu.com/s/118D8IWE48N49lWaBhsSAgQ 提取码: pgsi
地址三:https://pan.baidu.com/s/1i9v7_5ouL-ptq7ostcLxlw 提取码: wbhk

以上就是SpringMVC框架之处理文件上传(附照片上传Demo)主要内容,喜欢的可以点个赞哟~ ღ( ´・ᴗ・` )比心

发布了976 篇原创文章 · 获赞 230 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/qq_41855420/article/details/104116334