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. flowable+tomcat部署flowable项目,在线画流程图

    参考: flowable+tomcat部署flowable项目,在线画流程图

  2. google map api key配置

    https://console.cloud.google.com/google/maps-apis/apis/maps-backend.googleapis.com/credentials?proje ...

  3. centos 防火墙 iptables firewalld SELinux

    参考 Centos7 只启用iptables 禁用firewalld功能 java.net.NoRouteToHostException: 没有到主机的路由 相关内容 centos7 中才开始引用fi ...

  4. 洛谷 P1194 飞扬的小鸟 题解

    题面 这道题是一道隐藏的比较深的DP(我太蒟蒻了!) 设f[i][j]表示到第i列时高度为j的最少步数是多少: 求上升时的方案就是一个完全背包!,求下降时的方案就是一个01背包: 然后处理边界就能A掉 ...

  5. Mysql 表空间和 数据页空洞

    一.表空间1.表空间: innodb 引擎存储的最高层: 存放所有的数据2.独立表空间:Mysql 版本 5.6 后默认开启的单表单空间(1)Innodb 默认存储引擎页的大小为 16K :默认表空间 ...

  6. Javaweb实训-宠物医院-社区宠物医院的页面样式

    /* CSS Document */      /*        对于CSS来说  每一个元素默认的margin和padding就是0px.但是不同的浏览器会有一个默认的浏览器样式修改默认的marg ...

  7. jupyter notebook 使用多个python环境

    conda install nb_conda_kernels 执行上面的命令,然后启动notebook就可以选择conda中的所有环境了

  8. Almost Increasing Array CodeForces - 946G (dp)

    大意: 定义几乎递增序列为删除不超过一个数后序列严格递增. 给定序列, 求最少改变多少个数能变为几乎递增序列. 跟hdu5256类似,

  9. Solution for automatic update of Chinese word segmentation full-text index in NEO4J

    Solution for automatic update of Chinese word segmentation full-text index in NEO4J 1. Sample data 2 ...

  10. tab栏切换效果案例

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...