Servlet实现文件上传的三种方法总结
Servlet实现文件上传的三种方法总结
1.通过getInputStream()取得上传文件。
/** *Tochangethistemplate,chooseTools|Templates *andopenthetemplateintheeditor. */ packagenet.individuals.web.servlet; importjava.io.DataInputStream; importjava.io.FileOutputStream; importjava.io.IOException; importjavax.servlet.ServletException; importjavax.servlet.annotation.WebServlet; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; /** * *@authorBarudisshu */ @WebServlet(name="UploadServlet",urlPatterns={"/UploadServlet"}) publicclassUploadServletextendsHttpServlet{ /** *ProcessesrequestsforbothHTTP *GET
and *POST
methods. * *@paramrequestservletrequest *@paramresponseservletresponse *@throwsServletExceptionifaservlet-specificerroroccurs *@throwsIOExceptionifanI/Oerroroccurs */ protectedvoidprocessRequest(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ response.setContentType("text/html;charset=UTF-8"); //读取请求Body byte[]body=readBody(request); //取得所有Body内容的字符串表示 StringtextBody=newString(body,"ISO-8859-1"); //取得上传的文件名称 StringfileName=getFileName(textBody); //取得文件开始与结束位置 Positionp=getFilePosition(request,textBody); //输出至文件 writeTo(fileName,body,p); } //构造类 classPosition{ intbegin; intend; publicPosition(intbegin,intend){ this.begin=begin; this.end=end; } } privatebyte[]readBody(HttpServletRequestrequest)throwsIOException{ //获取请求文本字节长度 intformDataLength=request.getContentLength(); //取得ServletInputStream输入流对象 DataInputStreamdataStream=newDataInputStream(request.getInputStream()); bytebody[]=newbyte[formDataLength]; inttotalBytes=0; while(totalBytes/** *HandlestheHTTP * GET
method. * *@paramrequestservletrequest *@paramresponseservletresponse *@throwsServletExceptionifaservlet-specificerroroccurs *@throwsIOExceptionifanI/Oerroroccurs */ @Override protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ processRequest(request,response); } /** *HandlestheHTTP *POST
method. * *@paramrequestservletrequest *@paramresponseservletresponse *@throwsServletExceptionifaservlet-specificerroroccurs *@throwsIOExceptionifanI/Oerroroccurs */ @Override protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ processRequest(request,response); } /** *Returnsashortdescriptionoftheservlet. * *@returnaStringcontainingservletdescription */ @Override publicStringgetServletInfo(){ return"Shortdescription"; }// }
2.通过getPart()、getParts()取得上传文件。
body格式:
POSThttp://www.example.comHTTP/1.1 Content-Type:multipart/form-data;boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA ------WebKitFormBoundaryrGKCBY7qhFd3TrwA Content-Disposition:form-data;name="text" title ------WebKitFormBoundaryrGKCBY7qhFd3TrwA Content-Disposition:form-data;name="file";filename="chrome.png" Content-Type:image/png PNG...contentofchrome.png... ------WebKitFormBoundaryrGKCBY7qhFd3TrwA-- [html]viewplaincopy /** *Tochangethistemplate,chooseTools|Templates *andopenthetemplateintheeditor. */ packagenet.individuals.web.servlet; importjava.io.FileNotFoundException; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.InputStream; importjava.io.OutputStream; importjavax.servlet.ServletException; importjavax.servlet.annotation.MultipartConfig; importjavax.servlet.annotation.WebServlet; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importjavax.servlet.http.Part; /** * *@authorBarudisshu */ @MultipartConfig @WebServlet(name="UploadServlet",urlPatterns={"/UploadServlet"}) publicclassUploadServletextendsHttpServlet{ /** *ProcessesrequestsforbothHTTP *GET
and *POST
methods. * *@paramrequestservletrequest *@paramresponseservletresponse *@throwsServletExceptionifaservlet-specificerroroccurs *@throwsIOExceptionifanI/Oerroroccurs */ protectedvoidprocessRequest(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ Partpart=request.getPart("photo"); StringfileName=getFileName(part); writeTo(fileName,part); } //取得上传文件名 privateStringgetFileName(Partpart){ Stringheader=part.getHeader("Content-Disposition"); StringfileName=header.substring(header.indexOf("filename=\"")+10,header.lastIndexOf("\"")); returnfileName; } //存储文件 privatevoidwriteTo(StringfileName,Partpart)throwsIOException,FileNotFoundException{ InputStreamin=part.getInputStream(); OutputStreamout=newFileOutputStream("e:/workspace/"+fileName); byte[]buffer=newbyte[1024]; intlength=-1; while((length=in.read(buffer))!=-1){ out.write(buffer,0,length); } in.close(); out.close(); } ///** *HandlestheHTTP * GET
method. * *@paramrequestservletrequest *@paramresponseservletresponse *@throwsServletExceptionifaservlet-specificerroroccurs *@throwsIOExceptionifanI/Oerroroccurs */ @Override protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ processRequest(request,response); } /** *HandlestheHTTP *POST
method. * *@paramrequestservletrequest *@paramresponseservletresponse *@throwsServletExceptionifaservlet-specificerroroccurs *@throwsIOExceptionifanI/Oerroroccurs */ @Override protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ processRequest(request,response); } /** *Returnsashortdescriptionoftheservlet. * *@returnaStringcontainingservletdescription */ @Override publicStringgetServletInfo(){ return"Shortdescription"; } }
3、另一种较为简单的方法:采用part的wirte(StringfileName)上传,浏览器将产生临时TMP文件
/** *Tochangethistemplate,chooseTools|Templates *andopenthetemplateintheeditor. */ packagenet.individuals.web.servlet; importjava.io.IOException; importjava.io.PrintWriter; importjavax.servlet.ServletException; importjavax.servlet.annotation.MultipartConfig; importjavax.servlet.annotation.WebServlet; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importjavax.servlet.http.Part; /** *采用part的wirte(StringfileName)上传,浏览器将产生临时TMP文件。 *@authorBarudisshu */ @MultipartConfig(location="e:/workspace") @WebServlet(name="UploadServlet",urlPatterns={"/UploadServlet"}) publicclassUploadServletextendsHttpServlet{ /** *ProcessesrequestsforbothHTTP *GET
and *POST
methods. * *@paramrequestservletrequest *@paramresponseservletresponse *@throwsServletExceptionifaservlet-specificerroroccurs *@throwsIOExceptionifanI/Oerroroccurs */ protectedvoidprocessRequest(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ //处理中文文件名 request.setCharacterEncoding("UTF-8"); Partpart=request.getPart("photo"); StringfileName=getFileName(part); //将文件写入location指定的目录 part.write(fileName); } privateStringgetFileName(Partpart){ Stringheader=part.getHeader("Content-Disposition"); StringfileName=header.substring(header.indexOf("filename=\"")+10,header.lastIndexOf("\"")); returnfileName; } ///** *HandlestheHTTP * GET
method. * *@paramrequestservletrequest *@paramresponseservletresponse *@throwsServletExceptionifaservlet-specificerroroccurs *@throwsIOExceptionifanI/Oerroroccurs */ @Override protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ processRequest(request,response); } /** *HandlestheHTTP *POST
method. * *@paramrequestservletrequest *@paramresponseservletresponse *@throwsServletExceptionifaservlet-specificerroroccurs *@throwsIOExceptionifanI/Oerroroccurs */ @Override protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ processRequest(request,response); } /** *Returnsashortdescriptionoftheservlet. * *@returnaStringcontainingservletdescription */ @Override publicStringgetServletInfo(){ return"Shortdescription"; }// }
以上就是Servlet实现文件上传的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!