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、将图片上传至图片服务器(分布式文件系统)

springmvc+ajax异步上传图片的更多相关文章

  1. [Ajax] 使用Ajax异步上传图片文件(非Form表单提交)

    通过表单Form提交来上传文件的方式这里就不说了: 下面介绍,通过js中使用ajax异步上传图片文件: 新建一个html页面和一个一般处理程序即可: 涉及思路: //发送2次Ajax请求完成js异步上 ...

  2. ajax异步上传图片&SpringMVC后台代码

    function uploadPic(){ var options = { url : "/upload/updatePic.action", type : "post& ...

  3. 使用Ajax异步上传图片的方法(html,javascript,php)

    前两天项目中需要用到异步上传图片和显示上传进度的功能,于是找了很多外国的文章,翻山越岭地去遇上各种坑,这里写篇文章记录一下. HTML <form id="fileupload-for ...

  4. ajax异步上传图片三种方案

    转自:http://www.jb51.net/article/51180.htm 注:自己尝试了前两种,都可用: 目前常用的异步文件上传功能有几种,比较多见的如使用iframe框架形式,ajax功能效 ...

  5. ajax异步上传图片(TP5)

    直接上代码 PHP代码如下 /** * 上传 */ public function upload_photo(){ $file = $this->request->file('file') ...

  6. thinkPHP利用ajax异步上传图片并显示、删除

    近来学习tp5的过程中,项目中有个发帖功能,选择主题图片.如下: 利用原始的文件上传处理,虽然通过原始js语句能实时显示上传图片,但是这样的话会涉及很多兼容问题.使用ajax技术,实现选择性删除所选图 ...

  7. thinkphp5 不使用form,用input+ajax异步上传图片

    不支持$this->request->file()获取图片 后台接收文件请使用$_FILE 正文开始: HTML <div class="upload"> ...

  8. js 原生 ajax 异步上传图片

    <script type="text/javascript"> function upload() { var file1 = document.getElementB ...

  9. Ajax实现异步上传图片

    要求:点击页面浏览按钮后,选择需要上传的图片,页面无刷新,将上传的图片展示出来 开发流程 一:在页面编写表单代码和js代码 <!DOCTYPE html PUBLIC "-//W3C/ ...

随机推荐

  1. adobe Keychain mac

    Keychain password access This question has been Answered. janec2070563 May 8, 2018 11:07 AM I consta ...

  2. 配置tomcat-users.xml文件

    今天在学习登录日志保存时出现一系列错误,想查看浏览器后台的session,结果忘记怎么看用户名和密码了,下面是转载自民工也Coding的一篇文章, 文章链接为:http://www.cnblogs.c ...

  3. k8s-kubernetes-configmap存储

    存储 configMap configMap描述信息 ConfigMap功能在Kubernetes1.2版本中引入,许多应用程序会从配置文件.命令行参数或环境变量中读取配置信息. ConfigMap ...

  4. http 中指定head中Content-Encoding属性为gzip 转换过程中的一些问题

    项目环境: 对接的服务放在微服务中 提供接口给应用层调用 ,微服务放需要 接受参数 并且转换成压缩格式给 第三方服务 本来以为需要自己压缩,httpclint 中已经封装好了GzipCompressi ...

  5. pair常见用法

    pair的使用 关于pair 什么是pair 可以将pair看做一个内部有两个元素的结构体,且两个元素的类型是可以指定的. struct pair{ typename1 first; typename ...

  6. python中魔法方法__str__与__repr__的区别

    提出问题 当我们自定义一个类时,打印这个类对象或者在交互模式下直接输入这个类对象按回车,默认显示出来的信息好像用处不大.如下所示 In [1]: class People: ...: def __in ...

  7. DAX/PowerBI系列 - 累计总计(Cumulative Total, Running Total)

    DAX/PowerBI系列 - 累计总计(Cumulative Total) 2017/07/23 更新:B列公式(见最后) 2019/08/08 更新:在可视化数据的时候,一定要选择日期维度的日期列 ...

  8. Codeforces1256E_Yet Another Division Into Teams

    题意 n个人,每人有一个能力值a[i],要求分成多个队伍,每个队伍至少3个人,使得所有队伍的max(a[i])-min(a[i])之和最小. 分析 不会巧妙的dp,想了一天只想到了暴力的dp. 先排序 ...

  9. OCR(光学字符识别)技术简介

    OCR技术起源 OCR最早的概念是由德国人Tausheck最先提出的,1966年他们发表了第一篇关于汉字识别的文章,采用了模板匹配法识别了1000个印刷体汉字.早在60.70年代,世界各国就开始有OC ...

  10. CSA Lignts Out

    csa 算是热身题吧 如果是每次操作一行或一列,那么无论怎么操作,本质不同的行最多只有两种,本质不同的列也最多只有两种,那么只要把某一种行和某一种列全部翻转使得全为0即可 现在是同时操作一行一列,显然 ...