//判断提交过来的表单是否为文件上传菜单
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
//构造一个文件上传处理对象
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
Iterator iter;
try{
//解析表单中提交的文件内容
iter = upload.parseRequest(request).iterator();
while(iter.hasNext()){
FileItem item = (FileItem)iter.next();
if(!item.isFormField()){
//取出上传文件的名称
String name = item.getName();
String fileName = name.substring(name.lastIndexOf("\\")+1,name.length());
//上传文件以后的存储路径
String path = "D:upload//"+fileName;
//上传文件
File uploadFile = new File(path);
item.write(uploadFile);
request.setAttribute("path", "D:/upload/"+name);
//打印上传成功信息
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
// PrintWriter writer = response.getWriter();
// writer.write("<img src="+path+" width="+100+"></img>");
RequestDispatcher dispatcher = request.getRequestDispatcher("pictureUpload2.jsp");
dispatcher.forward(request, response);
}
}
}catch(Exception e){
e.printStackTrace();
System.out.println(e.toString());
}
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>图片上传</title>
<script type="text/javascript" src="js/jquery-1.7.1.js"></script>
<script type="text/javascript">
function check(){
if(!$("table").find("input[type='file']").val()){
alert("请先点击浏览选择图片");
return false;
}
var imageaddress = $("table").find("input[type='file']").val();
var image = imageaddress.lastIndexOf(".");
alert(image);
var type = imageaddress.substr(image);
alert(type);
if(type==".jpg" || type==".JPG" || type==".png" || type==".gif" || type==".GIF" || type==".bmp"){
$("#form1").submit();
}else{
alert("你所选择的文件不是图片,请选择图片上传!");
return false;
}
}
</script>
</head>
<body>
<form id="form1" method="post" action="Upload2" enctype="multipart/form-data">
<table border="1">
<tr>
<td colspan="2">
<c:choose>
<c:when test="${path!=null}">
<img src="${path}" width="125" height="150"/>
</c:when>
<c:otherwise>
<img src="images/j.jpg" width="125" height="150"/>
</c:otherwise>
</c:choose>
</td>
</tr>
<tr>
<td><input type="file" name="file" id="file"></td>
<td><input type="button" value="上传" οnclick="check();"></td>
</tr>
</table>
</form>
</body>
</html>