>>分享流行的Java框架以及开源软件,对孙卫琴的《精通Spring:Java Web开发技术详解》提供技术支持 书籍支持  卫琴直播  品书摘要  在线测试  资源下载  联系我们
发表一个新主题 开启一个新投票 回复文章 您是本文章第 22968 个阅读者 刷新本主题
 * 贴子主题:  springmvc+ajax异步上传图片 回复文章 点赞(0)  收藏  
作者:日月光华    发表时间:2020-07-02 11:46:01     消息  查看  搜索  好友  邮件  复制  引用

springmvc+ajax异步上传图片

1、javaweb传统的上传图片方式就是通过form表单提交
<form action="#" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传">
</form>

2、现在想要实现:点击文件表单的"浏览"按鈕后,文件异步上传,然后返回文件的路径,页面实时刷新显示刚才上传的图片。
  2.1、新建一个springboot项目picDemo
  
  pom.xml


<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

  application.properties


server.port=8090
server.servlet.context-path=/

  2.2、要实现图片异步上传,可以使用jquery.form.js插件。
  save.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>标题</title>
<script type="text/javascript" th:src="@{/js/jquery.js}"></script>
<script type="text/javascript" th:src="@{/js/jquery.form.js}"></script>
<style type="text/css">
.hidden {
    display:none;
}
</style>
</head>
<body>

<div id="film_save">
<form id="form" action="#" th:action="@{/film/save}" method="post" th:object="${film}" enctype="multipart/form-data">
    <input type="hidden" name="id" th:value="*{id}"/>

    <table class="table">
        <tr>
            <td>电影名称:</td>
            <td><input type="text" name="name" th:value="*{name}"/></td>
        </tr>
        <tr>
            <td>电影图片:</td>
            <td><input type="file" name="file" id="file" onchange="fileUpload()"/></td>
        </tr>
        <tr>
            <td><input type="hidden" id="imageUrl" name="imageUrl" value=""/></td>
            <td><img id="imgSrc" th:class="${film.imageUrl eq null or film.imageUrl eq ''}?hidden:''" th:src="'http://localhost:8080/image/' + ${film.imageUrl}" style="width:200px;"/></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="保存"/></td>
        </tr>
    </table>
</form>
    
<script type="text/javascript">
    function fileUpload() {
        var option = {
            type:'POST',
            url:'/film/uploadPic',
            dataType:'json',
            data:{
                fileName : 'file'
            },
            success:function(data){
                //把json串转换成json对象
                //var jsonObj = $.parseJSON(data);
                //alert(data);
            
                //返回服务器图片路径,把图片路径设置给img标签
                $("#imgSrc").attr("src",data.fullPath);
                
                // 显示图片
                $("#imgSrc").removeClass("hidden");
                
                //数据库保存相对路径
                $("#imageUrl").val(data.relativePath);
                //alert($("#imageUrl").val());
            }    
        };
        
        $("#form").ajaxSubmit(option);
    }
</script>
</div>
</body>
</html>

  2.3、后端代码
  IndexController


package com.oy;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class IndexController {

    @RequestMapping("/save")
    public Object save(Film film) {
        return "save";
    }
    
    @RequestMapping("/film/uploadPic")
    @ResponseBody
    public Object uploadPic(MultipartFile file) throws Exception {
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString().replace("-", "").toUpperCase()
                + "_" + oldName;
        System.out.println("上传的图片的newName: " + newName);
        
        File base = new File("d:/image/filmImage/");
        if (! base.exists()) {
            base.mkdirs();
        }
        
        // 保存文件
        file.transferTo(new File("d:/image/filmImage/" + newName));
        
        // 封装返回结果
        Map<String, Object> map = new HashMap<>();
        map.put("fullPath", "http://localhost:8090/image/" + newName);
        map.put("relativePath", newName);
        
        return map;
    }
}

  Film类:


public class Film {
    private Integer id; // 编号
    private String name; // 电影名称
    private String imageUrl; // 电影图片

    // getter和setter方法省略
}

  图片上传后,java返回的json数据为:


{
    "fullPath": "http://localhost:8090/image/E29C543179AD4B69B521EB542D9E735E_无标题.png",
    "relativePath": "E29C543179AD4B69B521EB542D9E735E_无标题.png"
}

  其中,fullPath为图片全路径。要实现图片上传后,图片刷新显示,还要再springboot中配置图片保存目录的路径映射:
  WebConfigurer类


package com.oy;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfigurer implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/image/**").addResourceLocations("file:D:/image/filmImage/");
    }
}

3、其他
  3.1、上面的demo是将图片保存目录的路径进行了映射。图片url与demo是在同一个域,都是http://localhost:8090,其实图片可以配置成其他的,比如http://localhost:8091,然后用外置的tomcat(非springboot内置)或nginx配置映射。
  3.2、将图片上传至图片服务器(分布式文件系统)


程序猿的技术大观园:www.javathinker.net
  Java面向对象编程-->多线程(下)
  JavaWeb开发-->自定义JSP标签(Ⅰ)
  JSP与Hibernate开发-->数据库事务的并发问题的解决方案
  Java网络编程-->客户端协议处理框架
  精通Spring-->虚拟DOM和render()函数
  Vue3开发-->Vue指令
  Maven 镜像地址大全
  git 仓库常用指令
  如何编写优雅的Spring架构API
  循序渐进,阿里架构师看完都赞叹的Redis分布式锁原理分析
  阿里巴巴为什么能抗住90秒100亿?看完这篇你就明白了!
  Mybatis-plus大数据量流式查询
  Redis夺命连环11问
  WebFlux 响应式编程初体验
  @Configuration注解的用法
  Spring MVC的拦截器的详细用法
  Spring Cloud构建微服务架构: 消息总线
  探讨通过Feign配合Hystrix进行调用时异常的处理
  RESTful API的最佳设计原则
  Spring5新特性之日志体系
  3分钟让你明白JSON是什么
  更多...
 IPIP: 已设置保密
楼主      
1页 1条记录 当前第1
发表一个新主题 开启一个新投票 回复文章


中文版权所有: JavaThinker技术网站 Copyright 2016-2026 沪ICP备16029593号-2
荟萃Java程序员智慧的结晶,分享交流Java前沿技术。  联系我们
如有技术文章涉及侵权,请与本站管理员联系。