java组件fileupload文件上传demo
在我们的web开发中,很多的时候都需要把本机的一些文件上传到web服务器上面去。
如:一个BBS系统,当用户使用这是系统的时候,能把本机的一些图片,文档上传到服务器上面去。然后其他用户可以去下载这些文件,那么这样的话,我们可以自己编程实现文件的上传,但是更好的方式是使用一些已有的组件帮助我们实现这种上传功能。
常用的上传组件:
Apache的CommonsFileUpload
JavaZoom的UploadBean
jspSmartUpload
FileUpload下载地址:
http://commons.apache.org/fileupload/
下载:commons-fileupload-1.2.2-bin.zip 得到:commons-fileupload-1.2.2.jar
http://commons.apache.org/io/
下载:commons-io-1.4-bin.zip 得到:commons-io-1.4.jar
upload.jsp
代码;
<%@pagelanguage="java"contentType="text/html;charset=UTF-8"%> <html> <head> <title>usingcommonsUploadtouploadfile</title> </head> <style> *{font-family:"宋体";font-size:14px} </style> <body> <palign="center">请您选择需要上传的文件</p> <formid="form1"name="form1"method="post"action="servlet/fileServlet"enctype="multipart/form-data"> <tableborder="0"align="center"> <tr> <td>上传人:</td> <td> <inputname="name"type="text"id="name"size="20"></td> </tr> <tr> <td>上传文件:</td> <td><inputname="file"type="file"size="20"></td> </tr> <tr> <td></td><td> <inputtype="submit"name="submit"value="提交"> <inputtype="reset"name="reset"value="重置"> </td> </tr> </table> </form> </body> </html>
FileUploadServlet.java代码:
packagecom.b510.example; importjava.io.File; importjava.io.IOException; importjava.util.*; importjavax.servlet.ServletConfig; importjavax.servlet.ServletContext; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importorg.apache.commons.fileupload.FileItem; importorg.apache.commons.fileupload.FileUploadException; importorg.apache.commons.fileupload.disk.DiskFileItemFactory; importorg.apache.commons.fileupload.servlet.ServletFileUpload; /** * *@authorXHW * *@date2011-7-26 * */ publicclassFileUploadServletextendsHttpServlet{ privatestaticfinallongserialVersionUID=-7744625344830285257L; privateServletContextsc; privateStringsavePath; publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ doPost(request,response); } publicvoidinit(ServletConfigconfig){ //在web.xml中设置的一个初始化参数 savePath=config.getInitParameter("savePath"); sc=config.getServletContext(); } publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ request.setCharacterEncoding("UTF-8"); DiskFileItemFactoryfactory=newDiskFileItemFactory(); ServletFileUploadupload=newServletFileUpload(factory); try{ Listitems=upload.parseRequest(request); Iteratoritr=items.iterator(); while(itr.hasNext()){ FileItemitem=(FileItem)itr.next(); if(item.isFormField()){ System.out.println("表单参数名:"+item.getFieldName()+",表单参数值:"+item.getString("UTF-8")); }else{ if(item.getName()!=null&&!item.getName().equals("")){ System.out.println("上传文件的大小:"+item.getSize()); System.out.println("上传文件的类型:"+item.getContentType()); //item.getName()返回上传文件在客户端的完整路径名称 System.out.println("上传文件的名称:"+item.getName()); FiletempFile=newFile(item.getName()); //上传文件的保存路径 Filefile=newFile(sc.getRealPath("/")+savePath,tempFile.getName()); item.write(file); request.setAttribute("upload.message","上传文件成功!"); }else{ request.setAttribute("upload.message","没有选择上传文件!"); } } } }catch(FileUploadExceptione){ e.printStackTrace(); }catch(Exceptione){ e.printStackTrace(); request.setAttribute("upload.message","上传文件失败!"); } request.getRequestDispatcher("/uploadResult.jsp").forward(request,response); } }
uploadResult.jsp代码:
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%> <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"> <html> <head> <title>uploadResult</title> <metahttp-equiv="pragma"content="no-cache"> <metahttp-equiv="cache-control"content="no-cache"> <metahttp-equiv="expires"content="0"> <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"> <metahttp-equiv="description"content="Thisismypage"> <!-- <linkrel="stylesheet"type="text/css"href="styles.css"> --> </head> <body> ${requestScope['upload.message']} <ahref="/upload/uploadFile.jsp">上传文件</a> </body> </html>
web.xml
代码:
<?xmlversion="1.0"encoding="UTF-8"?> <web-appversion="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <description>ThisisthedescriptionofmyJ2EEcomponent</description> <display-name>ThisisthedisplaynameofmyJ2EEcomponent</display-name> <servlet-name>FileUploadServlet</servlet-name> <servlet-class>com.b510.example.FileUploadServlet</servlet-class> <!--设置初始化参数--> <init-param> <param-name>savePath</param-name> <param-value>uploads</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>FileUploadServlet</servlet-name> <url-pattern>/servlet/fileServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> <welcome-file>uploadFile.jsp</welcome-file> </welcome-file-list> </web-app>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。