Springboot+Nginx实现伪图片上传
研究了一下本地的图片上传功能,随笔记录一下实现过程,很简陋,很多地方可以完善,建议自由发挥
Nginx配置
#图片存放位置
server{
listen 80;
server_name www.img.com;
location / {
root G:/exingImg;
}
}
host配置
127.0.0.1 www.img.com
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<form enctype="multipart/form-data" action="/upload" method="post">
选择图片:<input type="file" name="uploadFile">
<br>
<input type="submit" value="提交">
</form>
</div>
</body>
</html>
Controller
/**
* @author:lezzy
* @Date:2020/3/30 10:16
*/
@Controller
@RequestMapping("/")
@AllArgsConstructor
public class PageController {
//页面跳转不用管,跳转到img.html页面,使用thymeleaf模板
private ImageService imageService;
@RequestMapping("img")
public String goPage() {
return "img";
}
@RequestMapping("upload")
@ResponseBody
public Image uoload(MultipartFile uploadFile) throws IOException {
return imageService.uploadImg(uploadFile);
}
}
Service
/**
* @author:lezzy
* @Date:2020/3/30 13:59
*/
@Service
public class ImageServiceImpl implements ImageService {
private String localURL="G:/exingImg/";
private String HttpURL="http://www.img.com/";
private ImgDao imgDao;
public ImageServiceImpl(ImgDao imgDao){
this.imgDao=imgDao;
}
@Override
public Image uploadImg(MultipartFile uploadFile) throws IOException {
//获取真实图片名字 xxx.jpg
String fileName=uploadFile.getOriginalFilename();
//转换成小写
fileName=fileName.toLowerCase();
//按日期实现分文件夹保存
String datePath=new SimpleDateFormat("yyyy/MM/dd/").format((new Date()));
String realPath=localURL+datePath;
//这一步生成了G:/exingImg/2020/03/31/
File file=new File(realPath);
if (!file.exists()){
file.mkdirs();
}
//转换成URL路径
String uuid= UUID.randomUUID().toString();
int beginIndex=fileName.lastIndexOf(".");
String type=fileName.substring(beginIndex);
//8e80d708-2511-4ede-b53a-6b7820b6ce86.png
String uuidName=uuid+type;
//G:/exingImg/2020/03/31/8e80d708-2511-4ede-b53a-6b7820b6ce86.png
String uploadFilePath=realPath+uuidName;
//实现“上传功能”
uploadFile.transferTo(new File(uploadFilePath));
//nginx实现“网络地址”
//http://www.img.com/2020/03/31/8e80d708-2511-4ede-b53a-6b7820b6ce86.png
String url=HttpURL+datePath+uuidName;
//SpringDataJPA将网络地址存储到数据库中
Image img=new Image();
img.setTitle(url).setContent("lezzy");
imgDao.save(img);
return img;
}
}
Entity
/**
* @author:lezzy
* @Date:2020/3/30 10:55
*/
@Entity
@Table(name = "exingimg")
@Data
@Accessors(chain = true)
public class Image {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "title_url")
private String title;
@Column(name = "content_url")
private String content;
}
dao我就不贴了,用的是SpringDataJPA,继承JpaRepository就行
很简单,没啥需要注意的,注意前端的表单要使用多媒体标签,明天有空贴个ajax的图片上传,还是老规矩Springboot+Nginx
/这是一条分割线/
Ajax上传的前端代码
<!--上面的代码省略-->
<!--controller和service均没有改动-->
<div>
<form>
选择图片:<input type="file" name="uploadFile" id="uploadFile">
<input type="button" id="sure" value="提交">
</form>
<div id="showImg"></div>
</div>
</body>
<script src="jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#sure").on("click", upload);
})
function upload() {
var formData = new FormData();
//.append函数第一个参数为key,第二个参数为value,key要和Controller中的参数名一致
//$("")[0]是将jq对象转化为js对象,然后调用js对象的.files[0]函数。
formData.append("uploadFile", $("#uploadFile")[0].files[0]);
$.ajax({
type: "POST",
async: false,
url: "/upload",
data: formData,
//processData默认为true,数据将会被转化成字符串的形式被后台接受,这里要设置为false
processData: false,
//contentType表示发送数据的格式,默认值为application/x-www-form-urlencoded,无法传输复杂数据,传输文件要设置为false
contentType: false,
success: function (result) {
alert("上传成功");
var img = "<img src=" + result.title + ">";
$("#showImg").html(img);
},
});
}
</script>
ps:随笔记录一下,button标签放在form表单中,即使使用ajax也会刷新整个页面,要么在button标签中加入type=“button”,要么将按钮设置为submit然后在阻止提交表单,要么使用input标签 然后使用type="button"的格式再结合ajax使用,这样就不会使得页面刷新。