以前用commons和smartupload直接处理文件的上传,用struts就更不用管这些东西了,最近遇到不能用其他组件
处理上传文件的情况。
实际我以前没用过这个,我看request有个方法是getInputStream(),也不知道是不是处理上传文件的方法,我写了
点代码测试,但是总是不能成功,我上传的图片打开不能看,而且只有49字节。不知道这样做对不对,希望用过的前辈给指点一下,谢谢!以下是代码:处理上传文件的servletpublic class UploadServlet extends HttpServlet { @Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
InputStream sis = null;
FileOutputStream out = null;
try{
sis = req.getInputStream();
out = new FileOutputStream(new File(req.getRealPath("/upload"),"test.jpg"));
byte b[] = new byte[1024]; 
while(true){
int num = sis.read(b);//3,3,1
if(num==-1) break;
out.write(b,0,num);
}
System.out.println("文件上传成功");
}catch(Exception e){
e.printStackTrace();
System.out.println("上传文件失败");
}finally{
out.close();
sis.close();
}
}
}jsp页面
<%@page pageEncoding="utf-8"%>
<html>
<head>
<title>upload</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" />
<input type="submit" value="提交" />
</form>
</body>
</html>web.xml就不用帖了,肯定没错的。