>>分享流行的Java框架以及开源软件,对孙卫琴的《精通Spring:Java Web开发技术详解》提供技术支持 书籍支持  卫琴直播  品书摘要  在线测试  资源下载  联系我们
发表一个新主题 开启一个新投票 回复文章 您是本文章第 23106 个阅读者 刷新本主题
 * 贴子主题:  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
网站系统异常


系统异常信息
Request URL: http://www.javathinker.net/WEB-INF/lybbs/jsp/topic.jsp?postID=1016&replyID=0&skin=1&saveSkin=true&pages=1&replyNum=

java.lang.NullPointerException

如果你不知道错误发生的原因,请把上面完整的信息提交给本站管理人员