实现效果:
参考:Ajax简单异步上传图片并回显 <<------
下面是我自己通过参考自己实现的:
一:配置文件 spring-mvc.xml 中 引入
<!-- 配置文件解析器-->
<!-- 此处id为固定写法,不能随便取名-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"></property>
</bean>
二:编写HTML
<!-- 上传图片 -->
<div class="form-group">
<!-- 标签 -->
<div class="label">
<label>广告图片</label>
</div>
<!-- 上传 -->
<div class="field" style="margin-bottom: 20px;">
<input type="button" class="button bg-blue margin-left" value="+ 浏览上传" style="float:left;" required onclick="uploadPhoto()" />
<input type="file" id="adImage" name="img" required style="display: none;" />
<div class="tipss">*请上传广告资料!</div>
</div>
<!-- 回显 -->
<div class="field">
<img id="img" class="margin-left" height="169px" src="">
<!-- <label>图片预览效果</label><br /> -->
</div>
</div>
<!-- 提交按钮 -->
<div class="form-group">
<div class="field">
<input id="submit" class="button bg-main icon-check-square-o" type="button" value="提交">
</div>
</div>
三、编写js
//点击按钮选择图片事件
function uploadPhoto() {
$("#adImage").click();
}
//回显start
var small_img = document.querySelector('input[name=small_img]');
var img = document.querySelector('input[name=img]');
small_imgs = document.querySelector('#small_img');
imgs = document.querySelector('#img');
if (small_img) {
small_img.addEventListener('change', function() {
var file = this.files[0];
var reader = new FileReader();
// 监听reader对象的的onload事件,当图片加载完成时,把base64编码賦值给预览图片
reader.addEventListener("load", function() {
small_imgs.src = reader.result;
}, false);
// 调用reader.readAsDataURL()方法,把图片转成base64
reader.readAsDataURL(file);
$("img").eq(0).css("display", "block");
}, false);
}
if(img){
img.addEventListener('change', function() {
var file = this.files[0];
var reader = new FileReader();
// 监听reader对象的的onload事件,当图片加载完成时,把base64编码賦值给预览图片
reader.addEventListener("load", function() {
imgs.src = reader.result;
}, false);
// 调用reader.readAsDataURL()方法,把图片转成base64
reader.readAsDataURL(file);
$("img").eq(1).css("display", "block");
}, false);
}
//回显end
//Ajax请求
$("#submit").click(function () {
//判断图片是否为null
if ($("#adImage").val() == ''){
return;
}
//传递的参数
var formData = new FormData();
formData.append('adImage', document.getElementById('adImage').files[0]);
//给后台发送请求
$.ajax({
url: '/education_portal_system_war/ad/addAd.action',
type: 'post',
dataType: 'json',
data: formData,
contentType: false,
processData: false,
headers: {
// "Content-Type": "application/json",
"token": getCookieInfo("userInfo").t.token
},
success: function (data) {
if (data.status == 0) {
// 新增成功,返回列表页面
location.href = "adList.html";
}
},
error: function (e) {
console.log("请求失败:" + e);
}
})
})
四:编写图片上传工具类,返回类型为ResponseResult(Integer status,String errorMsg, T t)
public class UploadUtil {
//设置文件上传的路径
private static final String PATH = "F:/IdeaProjects/upload/";
/**
* 上传图片工具
* @param file 文件
* @return 结果集
*/
public static ResponseResult<String> upload(MultipartFile file){
//new一个响应结果集
ResponseResult<String> responseResult = new ResponseResult<>();
//当图片为null
if (null == file){
responseResult.setStatus(404);
responseResult.setErrMessage("请选择要上传的图片");
return responseResult;
}
//限制文件大小
if (file.getSize() > 10 * 1024 * 1024){
responseResult.setStatus(404);
responseResult.setErrMessage("文件的大小不能超过10M");
return responseResult;
}
//获取文件后缀,判断文件是否为图片
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
if (!("jpg, jpeg, gif, png".toUpperCase().contains(suffix.toUpperCase()))){
responseResult.setStatus(404);
responseResult.setErrMessage("请选择jpg,jpeg,gif,png格式的图片!");
return responseResult;
}
//执行至此,说明传入文件类型正确
//开始上传
File saveFile = new File(PATH);
if (! saveFile.exists()){
//若不存在该目录,则创建目录
saveFile.mkdir();
}
//重命名文件,防止重名导致文件覆盖
String fileName = new Date().getTime() + "." + suffix;
try {
//将文件保存到指定目录
file.transferTo(new File(PATH + fileName));
} catch (IOException e) {
e.printStackTrace();
responseResult.setStatus(404);
responseResult.setErrMessage("保存文件异常");
return responseResult;
}
//执行至此说明上传完成
responseResult.setStatus(0);
responseResult.setErrMessage("上传成功");
//存入文件名
responseResult.setT(fileName);
return responseResult;
}
}
五:编写Controller控制层
/**
* 广告控制层
*/
@RestController
@RequestMapping(value = "/ad")
public class AdController {
@Autowired
private IAdService adService;
/**
* 添加广告
* @param uploadFile
* @return
*/
@RequestMapping(value = "/addAd", method = RequestMethod.POST)
public ResponseResult addAd(@RequestParam(value = "adImage") MultipartFile uploadFile){
ResponseResult<String> result = UploadUtil.upload(uploadFile);
Ad ad = new Ad();
String fileName = result.getT();
ad.setAdImage(fileName);
ResponseResult responseResult = new ResponseResult();
try {
adService.addAd(ad);
responseResult.setStatus(0);
}catch (Exception e){
e.printStackTrace();
}
return responseResult;
}
}
六:Service层与Mapper层
太简单了,略。
有必要说一下动态SQL
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--nameSpace:mapper接口全路径-->
<mapper namespace="com.qf.system.mapper.AdMapper">
<insert id="addAd" parameterType="com.qf.cd.pojo.Ad">
insert into t_ad
<trim prefix="(" suffix=")" suffixOverrides="," prefixOverrides="">
<if test="adImage != null">
adImage,
</if>
<if test="adCreateTime !=null">
adCreateTime,
</if>
<if test="del !=null">
del,
</if>
</trim>
<trim prefix="values(" suffix=")" suffixOverrides=",">
<if test="adImage != null">
#{adImage},
</if>
<if test="adCreateTime !=null">
#{adCreateTime},
</if>
<if test="del !=null">
#{del},
</if>
</trim>
</insert>
</mapper>