图片上传流程优化

This commit is contained in:
xiongxiaoyang 2021-05-16 09:47:23 +08:00
parent 9de47ce697
commit 9d2c453bb0
9 changed files with 189 additions and 115 deletions

View File

@ -30,9 +30,9 @@ public class ResultBean<T> implements Serializable {
}
private ResultBean(ResponseStatus ResponseStatus) {
this.code = ResponseStatus.getCode();;
this.msg = ResponseStatus.getMsg();
private ResultBean(ResponseStatus responseStatus) {
this.code = responseStatus.getCode();;
this.msg = responseStatus.getMsg();
}
private ResultBean(T data) {
@ -44,30 +44,30 @@ public class ResultBean<T> implements Serializable {
/**
* 业务处理成功,无数据返回
* */
public static ResultBean ok() {
return new ResultBean();
public static ResultBean<Void> ok() {
return new ResultBean<>();
}
/**
* 业务处理成功有数据返回
* */
public static <T> ResultBean ok(T data) {
return new ResultBean(data);
public static <T> ResultBean<T> ok(T data) {
return new ResultBean<>(data);
}
/**
* 业务处理失败
* */
public static ResultBean fail(ResponseStatus ResponseStatus) {
return new ResultBean(ResponseStatus);
public static ResultBean<Void> fail(ResponseStatus responseStatus) {
return new ResultBean<>(responseStatus);
}
/**
* 系统错误
* */
public static ResultBean error() {
return new ResultBean(ResponseStatus.ERROR);
public static ResultBean<Void> error() {
return new ResultBean<>(ResponseStatus.ERROR);
}
}

View File

@ -68,6 +68,12 @@ public enum ResponseStatus {
* */
ES_SEARCH_FAIL(9001,"搜索引擎查询错误!"),
/**
* 文件相关错误
* */
FILE_DIR_MAKE_FAIL(10001,"目录创建失败"),
FILE_NOT_IMAGE(10002,"请上传图片类型的文件"),
FILE_SIZE_LIMIT(10003,"文件大小超出限制"),
/**
* 其他通用错误

View File

@ -1,6 +1,7 @@
package com.java2nb.novel.core.utils;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.apache.http.client.utils.DateUtils;
@ -11,6 +12,7 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Date;
import java.util.Objects;
@ -19,13 +21,14 @@ import java.util.Objects;
* 文件操作工具类
* @author 11797
*/
@UtilityClass
@Slf4j
public class FileUtil {
/**
* 网络图片转本地
* */
public static String network2Local(String picSrc,String picSavePath,String visitPrefix) {
public String network2Local(String picSrc,String picSavePath,String visitPrefix) {
InputStream input = null;
OutputStream out = null;
try {
@ -82,5 +85,21 @@ public class FileUtil {
}
/**
* 判断文件是否为图片
* @param file 需要判断的文件
* @return true:是图片false:不是图片
* */
@SneakyThrows
public boolean isImage(File file){
BufferedImage bi = ImageIO.read(file);
return bi != null;
}
}

View File

@ -11,6 +11,11 @@ spring:
generator:
write-numbers-as-strings: true
#上传文件的最大值1M
servlet:
multipart:
max-file-size: 1048576
#缓存类型ehcache(默认)redis
cache:
type: ehcache
@ -26,3 +31,5 @@ logging:
config: classpath:logback-boot.xml

View File

@ -2,28 +2,23 @@ package com.java2nb.novel.controller;
import com.java2nb.novel.core.bean.ResultBean;
import com.java2nb.novel.core.cache.CacheService;
import com.java2nb.novel.core.enums.ResponseStatus;
import com.java2nb.novel.core.exception.BusinessException;
import com.java2nb.novel.core.utils.Constants;
import com.java2nb.novel.core.utils.FileUtil;
import com.java2nb.novel.core.utils.RandomValidateCodeUtil;
import com.java2nb.novel.core.utils.RestTemplateUtil;
import com.java2nb.novel.core.utils.UUIDUtil;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Date;
import java.util.Objects;
@ -63,29 +58,35 @@ public class FileController {
}
/**
* 文件上传
* 图片上传
* @return
*/
@SneakyThrows
@ResponseBody
@PostMapping("/upload")
ResultBean upload(@RequestParam("file") MultipartFile file) {
@PostMapping("/picUpload")
ResultBean<String> upload(@RequestParam("file") MultipartFile file) {
Date currentDate = new Date();
try {
String savePath =
Constants.LOCAL_PIC_PREFIX + DateUtils.formatDate(currentDate, "yyyy") + "/" +
DateUtils.formatDate(currentDate, "MM") + "/" +
DateUtils.formatDate(currentDate, "dd") ;
String oriName = file.getOriginalFilename();
String saveFileName = UUIDUtil.getUUID32() + oriName.substring(oriName.lastIndexOf("."));
File saveFile = new File( picSavePath + savePath, saveFileName);
if (!saveFile.getParentFile().exists()) {
saveFile.getParentFile().mkdirs();
String savePath =
Constants.LOCAL_PIC_PREFIX + DateUtils.formatDate(currentDate, "yyyy") + "/" +
DateUtils.formatDate(currentDate, "MM") + "/" +
DateUtils.formatDate(currentDate, "dd");
String oriName = file.getOriginalFilename();
assert oriName != null;
String saveFileName = UUIDUtil.getUUID32() + oriName.substring(oriName.lastIndexOf("."));
File saveFile = new File(picSavePath + savePath, saveFileName);
if (!saveFile.getParentFile().exists()) {
boolean isSuccess = saveFile.getParentFile().mkdirs();
if(!isSuccess){
throw new BusinessException(ResponseStatus.FILE_DIR_MAKE_FAIL);
}
file.transferTo(saveFile);
return ResultBean.ok(savePath+"/"+saveFileName);
} catch (Exception e) {
log.error(e.getMessage(), e);
return ResultBean.error();
}
file.transferTo(saveFile);
if(!FileUtil.isImage(saveFile)){
//上传的文件不是图片
saveFile.delete();
throw new BusinessException(ResponseStatus.FILE_NOT_IMAGE);
};
return ResultBean.ok(savePath + "/" + saveFileName);
}

View File

@ -124,4 +124,36 @@ String.prototype.isNickName = function () {
function logout() {
$.cookie('Authorization', null,{ path: '/' });
location.reload();
}
}
function isImg(str) {
return !str.search("[.]+(jpg|jpeg|swf|gif|png|JPG|JPEG|SWF|GIF|PNG)$");
}
//校验图片上传
function checkPicUpload(file){
if(!isImg(file.value.substr(file.value.lastIndexOf(".")))){
layer.alert('只能上传图片格式的文件');
return false;
}
var fileSize = 0;
var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
if (isIE && !file.files) {
var filePath = file.value;
var fileSystem = new ActiveXObject("Scripting.FileSystemfileect");
var file = fileSystem.GetFile (filePath);
fileSize = file.Size;
}else {
fileSize = file.files[0].size;
}
fileSize=Math.round(fileSize/1024*100)/100; //单位为KB
if(fileSize>=1024){
layer.alert('上传的图片大小不能超过1M');
return false;
}
return true;
}

View File

@ -142,29 +142,32 @@
<script src="/layui/layui.all.js" type="text/javascript"></script>
<script src="/javascript/header.js" type="text/javascript"></script>
<script src="/javascript/user.js" type="text/javascript"></script>
<script src="/javascript/common.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
function picChange() {
var file = $("#file0").val(); //文件名称
if (file != "") {
$.ajaxFileUpload({
url : "/file/upload", //用于文件上传的服务器端请求地址
secureuri : false, //是否需要安全协议一般设置为false
fileElementId : "file0", //文件上传域的ID
dataType : "json", //返回值类型 一般设置为json
type : "post",
success : function(data) { //服务器成功响应处理函数
if (data.code == 200) {
$("#picImage").attr("src", data.data);
$("#picUrl").val(data.data);
}else {
layer.alert('图片上传失败');
if(checkPicUpload($("#file0")[0])) {
$.ajaxFileUpload({
url: "/file/picUpload", //用于文件上传的服务器端请求地址
secureuri: false, //是否需要安全协议一般设置为false
fileElementId: "file0", //文件上传域的ID
dataType: "json", //返回值类型 一般设置为json
type: "post",
success: function (data) { //服务器成功响应处理函数
if (data.code == 200) {
$("#picImage").attr("src", data.data);
$("#picUrl").val(data.data);
} else {
layer.alert(data.msg);
}
}
}
});
});
}
} else {
alert("请选择上传文件!");
}

View File

@ -138,6 +138,7 @@
<script src="/javascript/header.js" type="text/javascript"></script>
<script src="/javascript/user.js" type="text/javascript"></script>
<script src="/javascript/date.js" type="text/javascript"></script>
<script src="/javascript/common.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
search(1, 5);
@ -281,44 +282,46 @@
function picChange(bookId) {
var file = $("#file0").val(); //文件名称
if (file != "") {
if(checkPicUpload($("#file0")[0])) {
$.ajaxFileUpload({
url : "/file/upload", //用于文件上传的服务器端请求地址
secureuri : false, //是否需要安全协议一般设置为false
fileElementId : "file0", //文件上传域的ID
dataType : "json", //返回值类型 一般设置为json
type : "post",
success : function(data) { //服务器成功响应处理函数
if (data.code == 200) {
$.ajax({
type: "POST",
url: "/author/updateBookPic",
data: {'bookId':bookId,'bookPic':data.data},
dataType: "json",
success: function (data) {
if (data.code == 200) {
$.ajaxFileUpload({
url: "/file/picUpload", //用于文件上传的服务器端请求地址
secureuri: false, //是否需要安全协议一般设置为false
fileElementId: "file0", //文件上传域的ID
dataType: "json", //返回值类型 一般设置为json
type: "post",
success: function (data) { //服务器成功响应处理函数
if (data.code == 200) {
$.ajax({
type: "POST",
url: "/author/updateBookPic",
data: {'bookId': bookId, 'bookPic': data.data},
dataType: "json",
success: function (data) {
if (data.code == 200) {
location.reload();
location.reload();
} else {
} else {
lock = false;
layer.alert(data.msg);
}
},
error: function () {
lock = false;
layer.alert(data.msg);
layer.alert('网络异常');
}
})
},
error: function () {
lock = false;
layer.alert('网络异常');
}
})
} else {
layer.alert(data.msg);
}
}else {
layer.alert('图片上传失败');
}
}
});
});
}
} else {
alert("请选择上传文件!");
}

View File

@ -96,45 +96,48 @@
var file = $("#file0").val(); //文件名称
if (file != "") {
$.ajaxFileUpload({
url : "/file/upload", //用于文件上传的服务器端请求地址
secureuri : false, //是否需要安全协议一般设置为false
fileElementId : "file0", //文件上传域的ID
dataType : "json", //返回值类型 一般设置为json
type : "post",
success : function(data) { //服务器成功响应处理函数
if (data.code == 200) {
if(checkPicUpload($("#file0")[0])) {
$.ajax({
type: "POST",
url: "/user/updateUserInfo",
data: {'userPhoto':data.data},
dataType: "json",
success: function (data) {
if (data.code == 200) {
window.location.href = '/user/setup.html';
$.ajaxFileUpload({
url: "/file/picUpload", //用于文件上传的服务器端请求地址
secureuri: false, //是否需要安全协议一般设置为false
fileElementId: "file0", //文件上传域的ID
dataType: "json", //返回值类型 一般设置为json
type: "post",
success: function (data) { //服务器成功响应处理函数
if (data.code == 200) {
} else if (data.code == 1001) {
//未登录
location.href = '/user/login.html?originUrl=' + decodeURIComponent(location.href);
$.ajax({
type: "POST",
url: "/user/updateUserInfo",
data: {'userPhoto': data.data},
dataType: "json",
success: function (data) {
if (data.code == 200) {
window.location.href = '/user/setup.html';
} else {
layer.alert(data.msg);
} else if (data.code == 1001) {
//未登录
location.href = '/user/login.html?originUrl=' + decodeURIComponent(location.href);
} else {
layer.alert(data.msg);
}
},
error: function () {
layer.alert('网络异常');
}
})
},
error: function () {
layer.alert('网络异常');
}
})
} else {
layer.alert(data.msg);
}
}else {
layer.alert('图片上传失败');
}
}
});
});
}
} else {
alert("请选择上传文件!");
}