SpringBoot圖片上傳(一)


簡單描述:點擊上傳文件的圖標,上傳文件,上傳成功后,圖標編程上傳的圖片。

吐槽:文件上傳下載這種東西,總是感覺莫名的虛-_-||  也不知道是造了什么孽,(其實就是IO File這一塊的知識了解的不太深入)。

代碼:

//html代碼
<div class="col-md-6">
<label class="control-label flex" style="margin-top: 10px;">
上傳圖標<span class="star align-items">*</span>
</label>
<div class="">
<img th:src="@{/assets-new/apps/img/shangchuan.png}" id="imgPlanIcon"
width="35px" height="35px"/>
<input type="file" id="seledIcon" style="display:none"/>
</div>
<input type="hidden" name="planIcon" th:value="${plan?.planIcon}" id="planIcon"/>
</div>
//js代碼
$("#imgPlanIcon").on("click", function () {
$("#seledIcon").trigger("click");
});
//此js要放到初始化下,否則中間的file不會被識別,checkFile()是否初始化都無所謂
$("#seledIcon").on("change", function () {
if ($('#seledIcon').val().length == 0) {
return;
}
// 前端判斷選擇的文件是否符合要求
if (!checkFile()) {
// 重置file input
$('#seledIcon').replaceWith($('#seledIcon').val('').clone(true));
return;
}
// 上傳圖片到項目臨時目錄下
var url = rootPath + "serv/plan/upLoadImage";
var icon = $('#seledIcon')[0].files[0];
var fd = new FormData();
fd.append('icon', icon);
$.ajax({
url: url,
type: "post",
//Form數據
data: fd,
cache: false,
async: false,
contentType: false,
processData: false,
success: function (data) {
if (data.result == "success") {
// 上傳成功data為圖片路徑
var planIcon = data.fileName;
$('#planIcon').val(planIcon);
          //下邊兩行代碼用於回顯上傳成功后的圖標
var imgPlanIcon = rootPath + 'serv/plan/downLoadImage?planIcon=' + planIcon;
$('#imgPlanIcon').attr('src', imgPlanIcon);

        } else if (data.result == "fileIsEmpty") {
layer.msg("圖片內容為空!");
} else if (data.result == "formatError") {
layer.msg("請檢查圖片格式是否為jpg!");
} else if (data.result == "sizeTooBig") {
layer.msg("圖片大小超出512KB!");
} else if (data.result == "sizeError") {
layer.msg("圖片尺寸必須為60*60!");
} else {
layer.msg("上傳圖片失敗");
}
},
error: function () {
layer.msg("上傳圖片失敗,后台系統故障");
}
});
// 重置file input
$('#seledIcon').replaceWith($('#seledIcon').val('').clone(true));
});
function checkFile() {
var maxsize = 512 * 1024;
var errMsg = "圖片大小超出512KB!!!";
var browserCfg = {};
var ua = window.navigator.userAgent;
if (ua.indexOf("MSIE") >= 1) {
browserCfg.ie = true;
} else if (ua.indexOf("Firefox") >= 1) {
browserCfg.firefox = true;
} else if (ua.indexOf("Chrome") >= 1) {
browserCfg.chrome = true;
}
var obj_file = $('#seledIcon')[0];
var fileSize = 0;
var fileType;
if (browserCfg.firefox || browserCfg.chrome) {
fileSize = obj_file.files[0].size;
if (fileSize > maxsize) {
layer.msg(errMsg);
return false;
}
var fileName = obj_file.files[0].name;
fileType = fileName.slice(fileName.lastIndexOf(".") + 1).toLowerCase();
if (fileType != "jpg") {
layer.msg("請檢查圖片格式是否為jpg!");
return false;
}
} else if (browserCfg.ie) {
// ie瀏覽器,獲取不到filesize,暫時通過前台驗證,轉到后台處理
} else {
// 其它類型的瀏覽器,暫時通過前台驗證,轉到后台處理
}
return true;
}
//后台java代碼
//Controller中要聲明路徑
@Value("${constant.image_path}")
private String imagePath;

@Value("${constant.image_temp_path}")
private String imageTempPath;

@RequestMapping("/upLoadImage")
@ResponseBody
public Map<String, String> uploadFile(MultipartFile icon) throws Exception {
HashMap<String, String> map = new HashMap<>();
if (icon == null || icon.isEmpty()) {
map.put("result", "fileIsEmpty"); // 文件或內容為空
return map;
}
// 判斷圖片的格式是否符合要求
String fileName = icon.getOriginalFilename(); // 上傳的文件名
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
if (!"jpg".equals(suffix)) {
map.put("result", "formatError"); // 文件格式錯誤
return map;
}
BufferedImage image = ImageIO.read(icon.getInputStream());
if (image == null) {
map.put("result", "formatError"); // 文件格式錯誤
return map;
}
// 判斷圖片的大小是否符合要求
Long iconSize = icon.getSize() / 1024;
if (iconSize > 512) {
map.put("result", "sizeTooBig"); // 圖片超出指定大小
return map;
}

// 判斷圖片的尺寸是否符合要求
int width = image.getWidth();
int height = image.getHeight();
if (width != 60 || height != 60) {
map.put("result", "sizeError"); // 圖片尺寸不合適
return map;
}

File dirPath = new File(imageTempPath);
// 判斷文件夾是否存在
if (!dirPath.exists()) {
dirPath.mkdirs();
}
// 生成新的文件名稱
String uuid = UuidUtil.get32UUID();
String newFileName = uuid + "." + suffix;
// 將上傳文件保存到一個目標文件中
icon.transferTo(new File(imageTempPath + File.separator + newFileName));
map.put("result", "success");
map.put("fileName", newFileName);
return map;
} 
@RequestMapping("/downLoadImage")
public void downLoadFile(String planIcon, HttpServletResponse response) {
if (Tools.isEmpty(planIcon)) {
return;
}
File file = null;
file = new File(imagePath + File.separator + planIcon);
if (!file.exists()) {
file = new File(imageTempPath + File.separator + planIcon);
}

if (file.exists()) {
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
out = new BufferedOutputStream(response.getOutputStream());
// 設置response內容的類型
response.setContentType(new MimetypesFileTypeMap().getContentType(file));
// 設置頭部信息
response.setHeader("Content-disposition", "attachment;filename=" + planIcon);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

}
 

 

//constant.properties配置
# 上傳圖標的存放路徑
constant.image_path=D:\\image\\icon
# 上傳圖標的臨時存放路徑
constant.image_temp_path=D:\\image\\temp

總結


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM