原创

SSM 实训笔记 -15- Spring MVC + LayUI 实现图片上传

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://icode.blog.csdn.net/article/details/87702444

SSM 实训笔记 -15- Spring MVC + LayUI 实现图片上传

效果预览:

(一)前端部分:

(1)本篇适用 LayUI 前端框架,所以需要安装 LayUI,在 cmd 先进到项目下,在使用:

npm install layui-src

(2)前端页面 userInfo.html 文件代码:

注意:js、css 文件的路径、请求的 url 需要根据项目自行修改

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>网络云盘客户端-个人中心</title>
    <link rel="stylesheet" href="node_modules/layui-src/dist/css/layui.css">
    <script type="text/javascript" src="node_modules/jquery/dist/jquery.min.js"></script>
    <script type="text/javascript" src="node_modules/layui-src/dist/layui.all.js"></script>
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
    <legend>完善个人信息</legend>
</fieldset>
<div class="layui-row">
    <div class="layui-col-md6">
        <form class="layui-form" action="">
            <div class="layui-form-item">
                <label class="layui-form-label">真实姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="title" required  lay-verify="required" placeholder="请输入真实姓名" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">个人简介</label>
                <div class="layui-input-block">
                    <textarea name="desc" placeholder="请输入个人信息内容" class="layui-textarea"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="formDemo">确认更改</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>
    <div class="layui-col-md3">
        <div class="layui-upload layui-col-lg-offset2">
            <div class="layui-upload-list">
                <img class="layui-upload-img" id="demo1" src="../userPhoto/photo01.jpg" style="width: 50%">
                <p id="demoText"></p>
                <button type="button" class="layui-btn" id="test1">上传图片</button>
            </div>
        </div>
    </div>
</div>
<script>
    layui.use('upload', function(){
        var $ = layui.jquery,upload = layui.upload;
        //普通图片上传
        var uploadInst = upload.render({
            elem: '#test1',
            url: 'uploadHead.do',
            before: function(obj){
                //预读本地文件示例,不支持ie8
                obj.preview(function(index, file, result){
                    $('#demo1').attr('src', result); //图片链接(base64)
                });
            },
            done: function(res){
                //如果上传失败
                if(res.code > 0){
                    return layer.msg('上传失败');
                }
                //上传成功
                layer.msg("上传成功");
            },
            error: function(){
                //演示失败状态,并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst.upload();
                });
            }
        });
    });
</script>

</body>
</html>

(二)后端部分:

(1)pom 配置,添加两个 jar 包

commons-fileupload 和 servlet-api

    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.1.4.RELEASE</version>
    </dependency>

(2)SpringMVC 配置文件的配置

在 springmvc-servlet.xml 文件中添加一个 bean,例如:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--开启注解-->
    <!--<context:annotation-config> 是用于激活那些已经在 spring 容器里注册过的 bean
    (无论是通过 xml 的方式还是通过 package sanning 的方式 )上面的注解。-->
    <!--<context:component-scan> 除了具有<context:annotation-config>的功能之外-->
    <!--<context:component-scan> 还可以在指定的 package下扫描以及注册 javabean -->
    <context:annotation-config/>
    <context:component-scan base-package="com.xpwi.action"/>

    <!--json 消息转换器-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/html;charset=utf-8</value>
                            <value>application/json</value>
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>

    <!--文件上传-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <property name="maxUploadSize" value="20971520"/>
    </bean>
    
</beans>

(3)编写 UploadPhotoAction.java 文件:

package com.xpwi.action;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class UploadPhotoAction {

    @RequestMapping(value = "/uploadHead.do", method = RequestMethod.POST)
    @ResponseBody
    public int uploadHead(@RequestParam("file") MultipartFile file, HttpSession session) {
        try {
            if (file != null) {
                //获取文件名
                String fileName = file.getOriginalFilename();
                //截取扩展名
                String extName = fileName.substring(fileName.lastIndexOf("."));
                List list = new ArrayList();
                list.add(".jpg");
                list.add(".png");
                list.add(".jpeg");
                list.add(".gif");
                if(list.contains(extName.toLowerCase())){
                
                    //01获取服务器项目部署的路径,并在根目录下创建 myphoto 目录
                    //String realPath = session.getServletContext().getRealPath("myphoto");
                    //02也可以直接定义文件路径
                    String realPath = "D:\\space\\SSMBase\\src\\main\\webapp\\img";

                    String photoFileName = new Date().getTime()+extName;
                    String descPath = realPath + "\\" + photoFileName;
                    System.out.println(descPath);
                    file.transferTo(new File(realPath,photoFileName));
                    return 1;//成功
                }else {
                    return -1;//文件类型不正确
                }
            }else {
                return 0;//上传文件为空
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -1;//上传异常
        }
    }
}

(4)运行测试:

更多文章链接

文章最后发布于: 2019-02-19 13:06:24
展开阅读全文
0 个人打赏

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 1024 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览