1.首先下载一个jspsmartupload.jar包
2.添加到WEB-INF/lib文件夹中
3.示例:
jsp界面:
<form action="${pageContext.request.contextPath }/servlet/sellProductServlet" method="post" ENCTYPE="multipart/form-data" > 宝贝图片:<input type="file" name="filename"><br/><br/> <input type="submit" value="立刻发布"> </form>
sellProductServlet:
String url = null; SmartUpload su = new SmartUpload(); //开始上传文件 try { JspFactory fac=JspFactory.getDefaultFactory(); PageContext pageContext=fac.getPageContext(this, request,response, null, false, JspWriter.DEFAULT_BUFFER, true); su.initialize(pageContext); su.upload(); String pinstrution = su.getRequest().getParameter("pinstrution"); File file = su.getFiles().getFile(0); file.saveAs("/images/"+pcatagory+"/"+file.getFileName(),su.SAVE_VIRTUAL);//文件另存到tomcat部署的项目文件夹中,不是当前项目物理位置 //保存的是绝对路径 //file.saveAs("E:\\Workspaces\\MyEclipse 10\\SecondaryMarket\\WebRoot\\images\\"+pcatagory+"\\"+file.getFileName(),su.SAVE_PHYSICAL); url="./images/"+pcatagory+"/"+file.getFileName(); System.out.println(url); String imagepath = url;//文件上传 System.out.println(imagepath); ProductImple productImple = new ProductImple(); productImple.insert2Datebase(pcatagory, Float.parseFloat(pprice), pinstrution, pusername, imagepath, pname, Integer.parseInt(pnum)); response.sendRedirect("/SecondaryMarket/releaseSucc.jsp"); } catch (SmartUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); }路径问题在代码中我给了两种,一种是保存到tomcat下,推荐这样,这样便于移植,使用超级方便,想查看是否已经保存了,我是使用Myeclipse 10,你可以E:\Workspaces\MyEclipse 10\.metadata\.me_tcat\webapps\SecondaryMarket\images\Book去查看。
SmartUpload上传十分方便。smartUpload.jar下载地址:http://download.csdn.net/detail/tan313/8053135