jar包
配置文件
<!-- 文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
service层
public String uploadimg(MultipartFile avata, HttpServletRequest request) {
String fileurl = "";
if (avata.isEmpty()) {
System.out.println("无法找到文件");
return "";
} else {
System.out.println("文件长度: " + avata.getSize());
System.out.println("文件类型: " + avata.getContentType());
System.out.println("文件名称: " + avata.getName());
System.out.println("文件原名: " + avata.getOriginalFilename());
System.out.println("========================================");
String realPath = request.getSession().getServletContext()
.getRealPath("/upload");
File targetFile = new File(realPath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
System.out.println(realPath);
int i = avata.getOriginalFilename().lastIndexOf(".");// 返回最后一个点的位置
String extension = avata.getOriginalFilename().substring(i + 1);// 取出扩展名
String filename = UUID.randomUUID().toString() + "." + extension;
fileurl = filename;
try {
avata.transferTo(new File(realPath, filename));
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fileurl;
}
}
controller层
// 添加
@RequestMapping("add.do")
public String add(Item item,@RequestParam(value = "imgSize1File", required = false) MultipartFile file,HttpServletRequest request) {
String path = itemService.uploadimg(file, request);
item.setPic(request.getContextPath() + "/upload/" + path);
itemService.add(item);
return "redirect:findItem.do";
}
jsp页面
js脚本
function submitImgSize1Upload() {
var filePath = $("#imgSize1File").val();
if (filePath == "") {
$("#imgSize1File").after("<span class='messageImg' style='color: red'>商品图片不能为空!</span>");
} else {
var fileType = filePath.substring(filePath.lastIndexOf(".") + 1).toLowerCase();
$(".messageImg").remove();
if ("jpg" != fileType && "png" != fileType) {
$("#imgSize1File").after("<span class='messageImg' style='color: red'>请上传JPG,PNG格式的图片</span>");
$("#add").attr("disabled", "disabled");
} else if (document.getElementById("imgSize1File").files[0].size / 1024 > 2048) {
$("#imgSize1File").after("<span class='messageImg' style='color: red'>图片不能超过2MB</span>");
$("#add").attr("disabled", "disabled");
} else {
$("#add").removeAttr("disabled");
var reader = new FileReader();
reader.readAsDataURL(document.getElementById("imgSize1File").files[0]);
reader.onload = function(e) {
var img = $("#imgSize1ImgSrc")[0];
img.src = this.result;
}
}
}
}
//页面
<td>商品图片<span style="color: red;"> *</span></td>
<td>
<p>
<label></label> <img id='imgSize1ImgSrc' height="100" width="100" /> <span class='messageImg' style='color: black;'>图片不能超过2MB</span> <input type='file' id='imgSize1File' name='imgSize1File' class="file" onchange='submitImgSize1Upload()' />
</p>
</td>