昨天朋友做一个图片上传的需求,问到我了,正好我之前写过一个,觉得可能也会有其他人需要这个,所以现在整理出来供大家参考,希望对接大家有帮助。
前端(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;
}
}