jsp页面:
<body>
<form action="UploadServlet" method="post" enctype="multipart/form-data">
请选择一个文件上传
<input type="file" name="myFile">
<input type="submit" value="上传">
</form>
${msg}
</body>
注意:在form属性中要添加enctype属性,该属性告诉servlet表达提交的数据将会被编码并且具备多个部分,并且,其值一定是multipart/form-data,然后method一定是post
servlet部分:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
SmartUpload smartUpload=new SmartUpload();
ServletConfig config=this.getServletConfig();
smartUpload.initialize(config,request,response);
try{
//上传文件
smartUpload.upload();
//得到上传的文件对象
File smartFile=smartUpload.getFiles().getFile(0);
//保存文件
smartFile.saveAs("C:/"+smartFile.getFieldName(),smartUpload.SAVE_PHYSICAL);
}catch(SmartUploadException e){
e.printStackTrace();
}
String msg="Upload Success";
request.setAttribute("msg", msg);
RequestDispatcher rd=request.getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
最后,不要忘记在lib下导入jspsmart文件上传包哦,例如以下