图片上传
前言
开发工具:idea,MySQL
表单提交方式使用的是Ajax。
创建数据库和表
-- 创建数据库
CREATE DATABASE IF NOT EXISTS shoop DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
-- 创建一个文件上传的测试表
create table test_two(
testId int auto_increment primary key,
testPicture varchar(200)
)
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.springboot</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- spring boot mybatis依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
<!-- 添加thymeleaf支持:类似于jsp的视图模板 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
#数据源
spring.datasource.url=jdbc:mysql://localhost:3306/shoop?serverTimezone=Asia/Shanghai&useSSL=false&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
文件上传的辅助类(util)
@Configuration
public class UploadMapping implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//设置请求路径和文件物理路径映射关系
registry.addResourceHandler("/upfile/**").addResourceLocations("file:e:/proj_img/");
}
}
实体类(entity)
public class Test_two {
private Integer testId;
private String testPicture;
//省略getter和setter方法
}
接口(mapper)
@Mapper
public interface PictureMapper {
//图片上传
public int insert(Test_two test_two);
}
myBatis配置文件(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.springboot.mapper.PictureMapper">
<insert id="insert" parameterType="com.springboot.entity.Test_two">
insert into test_two(testPicture) values(#{testPicture})
</insert>
</mapper>
业务层(service)
public interface IPictureService {
//图片上传
public int insert(Test_two test_two);
}
业务实现层(service.impl)
@Service
public class PictureServiceImpl implements IPictureService {
@Resource
PictureMapper mapper;
@Override
public int insert(Test_two test_two) {
return mapper.insert(test_two);
}
}
逻辑控制层(Controller)
@Controller
@RequestMapping("/Test")
public class PictureController {
@Resource
IPictureService service;
//设置访问添加页面路径
@RequestMapping("/select")
public String select(){
return "/admin/insert";
}
//图片上传
@RequestMapping(value = "/insert")
@ResponseBody
public int insert(Test_two test_two, MultipartFile file) {
String imgFile = null;
//判断是否选择图片。如果用form表单提交用:if(file.isEmpty()){}
if (file == null) {
//没选为默认图片
imgFile = "/img/mr.jpg";
} else {
//生成新的文件名
String newFile = UUID.randomUUID() + "-" + file.getOriginalFilename();
//使用新文件名构建文件对象
File f = new File("e:/proj_img", newFile);
//判断上级目录是否存在,不存在则创建
if (!f.getParentFile().exists()) {
f.mkdirs();
}
try {
//将上传的图片保存到指定的位置
file.transferTo(f);
//记录上传文件的web访问路径
imgFile = "/upfile/" + newFile;
} catch (IOException e) {
e.printStackTrace();
}
}
//设置图片路径
test_two.setTestPicture(imgFile);
//保存对象到数据库
int num = service.insert(test_two);
if (num > 0) {
return 1;
} else {
return 0;
}
}
}
HTML页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/js/jquery-1.8.3.min.js"></script>
</head>
<script type="text/javascript">
//文件框选择文件时,图片标签自动切换图片
function showImg() {
//文件访问对象
var f = new FileReader();
f.onload = function (ev) {
img.src=ev.target.result;
}
f.readAsDataURL(file.files[0]);
}
</script>
<body>
<table>
<tr>
<td>商品图片</td>
<td>
<img src="/img/mr.jpg" width="80" height="100" id="img"/>
<br/>
<input type="file" name="file" id="file" onchange="showImg()"/>
</td>
</tr>
<tr>
<td>
<input type="button" value="上传" id="but">
</td>
</tr>
</table>
</body>
<script>
$("#but").click(function() {
//要知道file文件上传,并!=String类型的上传,所以我们要加上FormData()这个方法
var files = new FormData();
files.append('file', $('#file')[0].files[0]);
$.ajax({
type:"post",
url:"/Test/insert",
data:files,
dataType:"json",
processData: false,// 不处理数据
contentType: false, // 不设置内容类型
success:function(data) {
if(data == 1){
alert("上传成功");
}else{
alert("上传失败");
}
},
error:function() {
alert("上传时出现错误");
}
})
})
</script>
</html>
图片修改
修改需要先查询出所有图片,根据图片id查询单列的信息,最后进行修改。
需要的操作是:1.查询全部图片。2.查询单个图片。3.对图片进行修改然后刷新全部图片
接口(mapper)
@Mapper
public interface PictureMapper {
//查询全部图片
public List<Test_two> selectAll();
//根据图片id查询单列数据
public Test_two selectDan(Integer testId);
//修改图片
public int update(Test_two test_two);
}
myBatis配置文件(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.springboot.mapper.PictureMapper">
<select id="selectAll" resultType="com.springboot.entity.Test_two">
select testId,testPicture from test_two
</select>
<select id="selectDan" resultType="com.springboot.entity.Test_two">
select testId,testPicture from test_two where testId=#{testId}
</select>
<update id="update" parameterType="com.springboot.entity.Test_two">
update test_two set testPicture=#{testPicture} where testId=#{testId}
</update>
</mapper>
业务层(service)
public interface IPictureService {
//查询全部图片
public List<Test_two> selectAll();
//根据图片id查询单列数据
public Test_two selectDan(Integer testId);
//修改图片
public int update(Test_two test_two);
}
业务实现层(service.impl)
@Service
public class PictureServiceImpl implements IPictureService {
@Resource
PictureMapper mapper;
//查询全部图片
@Override
public List<Test_two> selectAll() {
return mapper.selectAll();
}
@Override
public Test_two selectDan(Integer testId) {
return mapper.selectDan(testId);
}
@Override
public int update(Test_two test_two) {
return mapper.update(test_two);
}
}
逻辑控制层(Controller)
@Controller
@RequestMapping("/Test")
public class PictureController {
@Resource
IPictureService service;
//查询全部图片
@RequestMapping("/selectAll")
public String selectAll(Model model){
List<Test_two> testList = service.selectAll();
model.addAttribute("testList",testList);
return "/admin/select";
}
//根据图片id查询单列数据
@RequestMapping("/selectDan")
@ResponseBody
public Object selectDan(Integer testId){
Test_two testTwo = service.selectDan(testId);
if(testTwo != null ){
return testTwo;
}else{
return 0;
}
}
@RequestMapping("/update")
@ResponseBody
public int update(Test_two test_two, MultipartFile file){
String imgFile = null;
//判断是否选择图片。如果用form表单提交用:if(!file.isEmpty()){}
if(file != null){
//生成新的文件名
String newFile = UUID.randomUUID()+"-"+file.getOriginalFilename();
//使用新文件名构建文件对象
File f = new File("e:/proj_img",newFile);
//判断上级目录是否存在,不存在则创建
if(!f.getParentFile().exists()){
f.mkdirs();
}
try {
//将上传的图片保存到指定的位置
file.transferTo(f);
test_two.setTestPicture("/upfile/"+newFile);
} catch (IOException e) {
e.printStackTrace();
}
}
//保存对象到数据库
service.update(test_two);
return 1;
}
}
HTML页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.com">
<head>
<meta charset="UTF-8">
<title>查询全部图片</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/css/bootstrap.min.css">
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
</head>
<script type="text/javascript">
//文件框选择文件时,图片标签自动切换图片
function showImg() {
//文件访问对象
var f = new FileReader();
f.onload = function (ev) {
img.src=ev.target.result;
}
f.readAsDataURL(file.files[0]);
}
</script>
<body>
<table>
<tr>
<td>编号</td>
<td>图片</td>
<td>操作</td>
</tr>
<th:block th:each="test:${testList}">
<tr>
<td class="testId" th:text="${test.testId}"></td>
<td>
<img th:src="${test.testPicture}" width="80" height="60"/>
</td>
<td>
<button onclick="select(this)" class="btn btn-default" data-toggle="modal" data-target="#myModal">修改</button>
</td>
</tr>
</th:block>
</table>
<!-- 模态框(Modal) -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
<h4 class="modal-title" id="myModalLabel">
修改
</h4>
</div>
<div class="modal-body">
<input type="type" id="testId"/>
<div>
请输入修改名称: <img src="" width="80" height="100" id="img"/>
<br/>
<input type="file" name="file" id="file" onchange="showImg()"/>
<input type="hidden" name="testPicture" id="testPicture"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭
</button>
<button type="button" id="sub" class="btn btn-primary">
提交更改
</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
</body>
<script>
//查询
function select(res) {
var testId = $(res).parent().siblings(".testId").html();
$.ajax({
url:"/Test/selectDan",
data:{
testId:testId
},
success: function(data){
if(data != 0){
$("#testId").val(data.testId);
//把图片路径赋给src
var picture= data.testPicture
document.getElementById("img").src = picture;
//默认图片路径,如果不修改图片,还是这个路径
$("#testPicture").val(data.testPicture);
}
},
error:function (data) {
alert("没有该商品信息");
},
});
}
//修改
$("#sub").click(function() {
//var testId = $("#testId").val();
var files = new FormData();
files.append('file', $('#file')[0].files[0]);
files.append('testId',$("#testId").val());
files.append('testPicture',$("#testPicture").val());
$.ajax({
type:"post",
url:"/Test/update",
data:files,
dataType:"json",
processData: false,// 不处理数据
contentType: false, // 不设置内容类型
success:function(data) {
if(data == 1){
alert("修改成功");
//跳转到首页
window.location.href = 'http://localhost:8080/Test/selectAll';
}else{
alert("修改失败");
}
},
error:function() {
alert("修改时出现错误");
}
})
})
</script>
</html>
以上就是用Ajax进行图片上传与修改如果对各位有帮助,请点个赞。项目源码https://pan.baidu.com/s/1yt3brsDdrQL72Ii9itM73Q 提取码:l3we