使用很简单的办法上传图片
1. 首先把上传的页面写好
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>使用很简单的办法上传图片</title>
<head th:include="include::header">
<link rel="shortcut icon" href="favicon.ico">
<link href="/css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
<link href="/css/font-awesome.css?v=4.4.0" rel="stylesheet">
<link href="/css/animate.css" rel="stylesheet">
<link href="/css/style.css?v=4.1.0" rel="stylesheet">
</head>
<style>
h3{
color: #000023;
display: block;
line-height: 26px;
text-align: left;
}
h4{
color: #3b0000;
margin-left: 8px;
}
.fist{
background-color: #b9bebb;
height: 26px;
}
.set-status{
margin-left: 66px;
margin-top: 10px;
}
.ps{
color: #272727;
font-family: "楷体";
font-size: 16px;
}
</style>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
<div class="row">
<div class="col-sm-12">
<div class="ibox float-e-margins">
<div class="ibox-content">
<form method="POST" enctype="multipart/form-data" id="signupForm" >
<!--获取到xMainHome的id 方便前后台的数据传输-->
<input id="id" type="hidden" name="id" th:value="${wxMainHD.id}">
<div class="fist-picture">
<div class="fist" >
<h3>首页图</h3>
</div>
<label class="fist-show" style="margin-top: 6px">
<h4> 首页展示图(请点击黑色线框中选择需要上传的图片):</h4>
</label>
<!--首页展示图片上传框-->
<div class="form-group">
<!--设置图片上传类型以及函数触发事件-->
<input accept=".jpg,.jpeg,.png" type="file" class="files" id="mainLogoHome" name="mainLogo" style="display:none;" onchange="fileChange(event)">
<div class="picture" style="margin-left: 40px;border:1px solid #000">
<!--显示首页图片区域-->
<img th:src="${wxMainHD.mainLogo}" id="img-change" width="600px" height="350px"><br>
<span style="color:grey;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;">图片仅支持JPG/JPEG/PNG格式,大小不超过2M</span>
</div>
</div>
</div>
<div class="form-group">
<div class="save-content" style="margin-left: 130px;margin-top: 10px">
<button id="b1" type="submit" class="btn btn-primary" >上传图片</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div th:include="include::footer"></div>
<script type="text/javascript" src="/js/jquery-labelauty.js"></script>
<script type="text/javascript" src="/js/wangEditor.js"></script>
<script type="text/javascript" src="/js/appjs/sys/WxMainHome/editIn.js"></script>
</body>
</html>
JS:
$(function () {
validateRule();
})
var data=[];
$.validator.setDefaults({
submitHandler : function() {
if($('#img-change').attr("src").length==0){
alert("请上传首页图mainLogo!");
}else{
$('#b1').attr("disabled","true");
saveEditIn();
}
}
});
$("#img-change").click(function () {
$("#mainLogoHome").click();
});
var fileChange = function (event) {
var files = event.target.files, file;
if (files && files.length > 0) {
file = files[0];
if (file.size > 1024 * 1024 * 2) {
alert('图片大小不能超过2MB!');
return false;
}
var URL = window.URL || window.webkitURL;
var imgURL = URL.createObjectURL(file);
$("#img-change").attr("src", imgURL);
}
};
var saveEditIn = function () {
layer.load(1,{
shade: [0.5,"#6a6a6a"]
})
var formData = new FormData();
var id = $("#id").val();
var homeId = $("#homeId").val();
var imgDetail = editor.txt.html();
var status = $('input:radio[name="status"]:checked').val();
console.log(imgDetail)
console.log(status)
console.log(document.getElementById("mainLogoHome").files[0]);
if(document.getElementById("mainLogoHome").files[0]==="undefined"||document.getElementById("mainLogoHome").files[0]==null){
formData.append("mainLogo",$("#img-change").attr("src"));
} else {
formData.append("file",document.getElementById("mainLogoHome").files[0],"mainLogo"+suffix($("#mainLogoHome").val()));
}
formData.append("id",id);
formData.append("homeId",homeId);
formData.append("imageUrl",imgDetail);
formData.append("status",status);
$.ajax({
type:"POST",
data:formData,
url:"/sys/WxMainHome/saveEditIn",
async : false,
processData:false,
contentType: false,
success : function(r) {
if (r.code == 0) {
parent.layer.msg("内页编辑成功");
parent.reLoad();
var index = parent.layer.getFrameIndex(window.name);
parent.layer.close(index);
} else {
parent.layer.msg(r.msg);
}
}
})
}
var suffix = function (name) {
var index1=name.lastIndexOf(".");
var index2=name.length;
var suffix=name.substring(index1+1,index2);
return "."+suffix;
}
2. 上传图片工具类util
上传 FileUtils,就是将图片保存到盘符当中,
package com.ultrapower.life.admin.util;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
public class FileUtils {
public static String save(String dir, MultipartFile file) {
if (file.isEmpty()) {
return null;
}
String fileName = getPicRandomName(file.getOriginalFilename());
File upload = getFileDir(dir);
File dest = new File(upload,fileName);
try {
file.transferTo(dest);
return Constant.imageUrl + dir+"/" + fileName;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String getPicRandomName(String picName) {
String name = "";
String randomName = RandomValues.getRandoms(16);
int index = picName.lastIndexOf(".");
if(index<0)
return randomName+".png";
String picType = picName.substring(index);
name = randomName + picType;
return name;
}
public static File getFileDir(String id) {
String childPath="/";
String filePath = Constant.imageFilePath;
if (StringUtils.isNotBlank(id)){
childPath = id+"/";
}
File upload=new File(filePath,childPath);
if(!upload.exists()){
upload.mkdirs();
}
System.out.println(upload.getAbsolutePath());
return upload;
}
}
保存图片时随机生成文件名
RandomValues
package com.ultrapower.life.admin.util;
public class RandomValues {
private static String[] randomValues = new String[]{"0","1","2","3","4","5","6","7","8","9","_","a", "b", "c", "d", "e", "f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
private static String[] randomValuesNumber = new String[]{"0","1","2","3","4","5","6","7","8","9"};
public static String getRandoms(int lenght) {
StringBuffer str = new StringBuffer();
for(int i = 0;i < lenght; i++){
Double number=Math.random()*(randomValues.length-1);
str.append(randomValues[number.intValue()]);
}
return str.toString();
}
public static String getRandomsNumber(int lenght) {
StringBuffer str = new StringBuffer();
for(int i = 0;i < lenght; i++){
Double number=Math.random()*(randomValuesNumber.length-1);
str.append(randomValuesNumber[number.intValue()]);
}
return str.toString();
}
}
图片信息
ImgInfo
package com.ultrapower.life.admin.util;
import lombok.Data;
import java.util.Arrays;
@Data
public class ImgInfo {
private Integer errno;
private String[] data;
@Override
public String toString() {
return "ImgInfo [errno=" + errno + ", data=" + Arrays.toString(data) + "]";
}
}
3.controller层
@Log("编辑内页")
@RequiresPermissions("sys:WxMainHome:editIn")
@GetMapping("/editIn/{id}")
public String editIn(Model model, @PathVariable("id") Integer id){
WxHomeDetailVO wxMainHD = wxMainHomeService.getId(id);
model.addAttribute("wxMainHD",wxMainHD);
return prefix + "/editIn";
}
@RequiresPermissions("sys:WxMainHome:editIn")
@PostMapping("/saveEditIn")
@ResponseBody
public R saveEditIn(@RequestParam(value = "file",required = false) MultipartFile file, WxMainHome wxMainHome,
WxMainDetail wxMainDetail){
boolean flag = wxMainHomeService.saveInfo(file,wxMainHome);
if (flag) {
return R.ok();
} else {
return R.error("保存失败");
}
}
4. service及其实现类
service
boolean saveInfo(MultipartFile files, WxMainHome wxMainHome);
service实现类
@Override
@Transactional(rollbackFor=Exception.class)
public boolean saveInfo(MultipartFile files, WxMainHome wxMainHome) {
String mainLogo = "";
String originalFileName = "";
if (files != null){
try {
byte[] fileBytes =files.getBytes();
originalFileName = files.getOriginalFilename();
if (originalFileName.contains("mainLogo")){
String save = FileUtils.save(mainLogo,files);
wxMainHome.setMainLogo(save);
}
} catch (IOException e) {
e.printStackTrace();
}
}
wxMainHome.setUpdateTime(LocalDateTime.now());
boolean flag = wxMainHomeMapper.saveInfo(wxMainHome);
return flag;
}
5. mapper文件
(1)接口
Boolean saveInfo(WxMainHome wxMainHome);
(2)xml
<?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">
<mapper namespace="com.ultrapower.life.mapper.WxMainHomeMapper">
<resultMap id="ResultMap" type="WxMainHome">
<id property="id" column="id"/>
<result property="position" column="position"/>
<result property="type" column="type"/>
<result property="name" column="name"/>
<result property="status" column="status"/>
<result property="mainLogo" column="main_logo"/>
<result property="createTime" column="create_time"/>
<result property="updateTime" column="update_time"/>
</resultMap>
<!--将首页图地址更改-->
<update id="saveInfo" parameterType="com.ultrapower.life.entity.WxMainHome">
update wx_main_home
set
status=#{status},
main_logo=#{mainLogo},
update_time=#{updateTime}
where id=#{id}
</update>
</mapper>
由于我们需要将上传的图片放到盘符上,因此需要在
application-dev.yml文件里设置路径
这里设置好就可以了,还需要在本地搭建一个Nginx,方便开发
好了,我们来演示一下:
选择图片之前:
点击之后:
图片加载进来了:
保存之后:
OK 了!!!