昨天朋友做一個圖片上傳的需求,問到我了,正好我之前寫過一個,覺得可能也會有其他人需要這個,所以現在整理出來供大家參考,希望對接大家有幫助。
前端(jsp)
<form id="orgLogoAddrUploadForm" method="post" target="upload_result"
action="${webRoot}/articlePush/uploadImage" class="form-horizontal col-sm-12 form"
style="margin-left: 0; display: none;" enctype="Multipart/form-data">
<div class="form-group" style="margin-bottom: 0;">
<div id="thumbnailUploadContainer" class="col-sm-10">
<span style="font-weight: bolder;">圖片上傳:</span>
<input id="orgLogoAddrImageFile" name="imageFile" type="file" class="form-
control" style="width: 180px; display: inline;" />
<button id="uploadButton" class="btn btn-primary" type="button">上傳圖片 </button>
<span style="color:red;">*</span>
</div>
</div>
</form>
具體各個標籤什麼作用就不用介紹了吧,不懂的,大家自行百度!
前端(js)
// 圖片上傳按鈕
$("#uploadButton").on("click", function() {
var image = $("#orgLogoAddrImageFile").val();
if (image==null || image.length<=0) {
alert("請選中上傳的圖片!");
return;
}
$("#orgLogoAddrUploadForm").submit();
});
後端(springmvc+mybatis)
@LoggerAnno(funcName="上傳新聞縮略圖")
@RequestMapping("/uploadArticleImage")
public String uploadArticleImage(HttpServletRequest request, Model model) {
MultipartRequest mrequest = (MultipartRequest) request;
MultipartFile mfile = mrequest.getFile("imageFile");
// 判斷文件是否爲空
if (mfile == null || mfile.getSize() == 0) {
BaseModel result = new BaseModel();
result.setSuccess(false);
result.setMessage("請選擇上傳文件");
try {
model.addAttribute("uploadResult", JSONUtils.toString(result));
} catch (IOException e) {
logger.error("", e);
throw new RuntimeException();
}
//這是個頁面地址,因爲我上面設置了靜態變量,這邊就不展示了
return UPLOAD_RESULT_PAGE;
}
// long imgSize=1000; //默認200K
long imgSize = 2* 1024 * 1024;//默認2M
String resultMsg = "2M";
// 判斷文件大小是否超過設定的值
if (mfile.getSize() > imgSize) {
BaseModel result = new BaseModel();
result.setSuccess(false);
result.setMessage("文件大小不能超過"+resultMsg+", 請重新上傳");
try {
model.addAttribute("uploadResult", JSONUtils.toString(result));
} catch (IOException e) {
logger.error("", e);
throw new RuntimeException();
}
return UPLOAD_RESULT_PAGE;
}
try {
// 文件的後綴
String postFix = SystemFileUtils.getFilePostFix(mfile.getOriginalFilename());
// 上傳相對路徑, 按月創建文件夾,根據自己的實際情況設置
Date date = new Date();
DateTime dt = new DateTime(date);
int year = dt.getYear(); // 年
int month = dt.getMonthOfYear(); // 月
// 文件名
String fileName = SystemStringUtils.getUUID() + postFix;
String uploadPath = this.systemConfigs.getArticleThumbnailUploadPath() + "/" + year;
if(month<10){
uploadPath += "0";
}
uploadPath += month +"/" + fileName;
// 保存路徑 這裏填寫服務器地址+tomcat下指定保存圖片的文件夾
String savePath = this.systemConfigs.getUploadSaveBasePath() + uploadPath;
// 判斷文件夾是否存在,不存在則新建
File saveFile = new File(savePath);
if (!saveFile.getParentFile().exists()) {
saveFile.getParentFile().mkdirs();
}
Image srcImg=javax.imageio.ImageIO.read(mfile.getInputStream());
// 保存圖片文件
InputStream inputStream = mfile.getInputStream();
FileUtils.copyInputStreamToFile(inputStream, saveFile);
// 設置縮略圖入庫路徑
String accessPath = this.systemConfigs.getUploadAccessBasePath() + uploadPath;
// 返回數據
BaseModel result = new BaseModel();
Map<String, Object> data = new HashMap<String, Object>();
data.put("type", "image");
data.put("accessPath", accessPath);
result.setData(data);
model.addAttribute("uploadResult", JSONUtils.toString(result));
return UPLOAD_RESULT_PAGE;
} catch (Exception e) {
logger.error("", e);
BaseModel result = new BaseModel();
result.setSuccess(false);
result.setMessage("上傳失敗");
try {
model.addAttribute("uploadResult", JSONUtils.toString(result));
} catch (IOException e2) {
logger.error("", e2);
throw new RuntimeException();
}
//這裏是返回的視圖(jsp頁面)
return UPLOAD_RESULT_PAGE;
}
}