Servlet上传文件

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq378741744/article/details/83636186
准备工作:要到http://commons.apache.org/fileupload/download_fileupload.cgi下载上传文件需要的组件类库并且到
http://commons.apache.org/io/download_io.cgi上下载其IO组件,再有了这两个组件之后我们就可以编写一个上传的Servlet程序了。
1.建立一个jsp文件里面有文件域,能够提交给要处理数据的servlet程序的映射路径,form标签中有enctype="multipart/form-data"这条属性。
2.然后我们新建一个处理该Post方法的servlet程序,设置映射路径为jsp文件中对应的映射路径,让后,我们修改配置文件,在servlet启动时,添加一条属性,是存放文件的目录。
3.在servlet init()方法里读取项目路径和上传文件存放目录,然后编写doPost()方法。具体如下:
第一、在init()方法中利用config取得保存路径和工程文件位置。
第二、在doPost方法中实现上传的数据处理。首先需要设置一下数据的编码格式response.setCharacterEncoding("UTF-8");,以防下面出现乱码现象。然后,创建一个DiskFileItemFactory对象factory,再用ServletFileUpload类创建一个对象file,将factory对象包装起来,再用file的parseRequest()方法接收request的数据,放入List对象lst中,用迭代器it接收遍历file内容,用FileItem对象fileItem循环接收,读取数据,用fileItem的isFormField()方法判断是否是上传文件还是表单数据项,如果是上传文件,那么我们先需要创建一个tempFile对象,利用其getName()方法获得文件除了路径外的真实名称,再用init()方法获得的ServletContent对象获得工程的路径(sc.getRealPath("/")),加上获得的保存目录,构成上传文件的具体目录,在新建一个File对象,利用已得到的文件完全路径建立新对象realFile最后永fileItem的write()方法包装realFile将其写入硬盘,完成上传的功能
init()方法代码
public void init(ServletConfig config) throws ServletException {
savePath=config.getInitParameter("savePath");
sc=config.getServletContext();
super.init();

}
doPost()方法代码
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload file=new ServletFileUpload(factory);
try {
List lst=file.parseRequest(request);
Iterator it=lst.iterator();
while(it.hasNext()){
FileItem fileItem=(FileItem)it.next();
if(fileItem.isFormField()){
System.out.println("表单数据的 名称:"+fileItem.getFieldName()+
" 表单数据的内容"+fileItem.getString("UTF-8"));
}
else{
if(fileItem.getName()!=null&&!fileItem.getName().equals("")){
System.out.println("上传文件的名称:"+fileItem.getName());
System.out.println("上传文件的大小:"+fileItem.getSize());
System.out.println("上传文件的类型:"+fileItem.getContentType());
File tempFile=new File(fileItem.getName());
File realFile=new File(sc.getRealPath("/")+savePath,tempFile.getName());
try {
fileItem.write(realFile);
request.setAttribute("upLoad message","上传成功");
} catch (Exception e) {
request.setAttribute("upLoad message","上传失败");
e.printStackTrace();
}
}
}
}
} catch (FileUploadException e) {
request.setAttribute("upLoad message","上传失败");
e.printStackTrace();
}
}
展开阅读全文
博主设置当前文章不允许评论。

servlet 上传文件

12-18

我想通过servlet接受输入流,并放到mysql数据库中。先不要说用组件什么的了。rn**************************************************rnform表单:rnrnrn rnrnrnrnrnrnrn**************************************************rnservlet:rnrnpackage upload_file;rnimport javax.servlet.*;rnimport javax.servlet.http.*;rnimport java.io.*;rnimport java.sql.*;rnpublic class up_file extends HttpServletrnrn public void doPost(HttpServletRequest request,HttpServletResponse response)rn throws IOException,ServletExceptionrn rn rn tryrn Class.forName("com.mysql.jdbc.Driver");rn rn catch(ClassNotFoundException err_1)rn PrintWriter out=response.getWriter();rn out.print("err1"+err_1); rn rn tryrn Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test_search","****","******");rn Statement stmt=conn.createStatement();rn [color=#FF0000]InputStream is=request.getInputStream();[/color]rn String sql_1="insert into big_data(t_data)Values("+is+")";rn stmt.execute(sql_1);rn stmt.close();rn conn.close();rn rn catch(SQLException err_2)rn rn PrintWriter out=response.getWriter();rn out.print("err2"+err_2); rn rn rn public void doGet(HttpServletRequest request1,HttpServletResponse response1)rn throws IOException,ServletExceptionrn rn PrintWriter out=response1.getWriter();rn out.print("use post");rn rnrn*********************************************************rnrn我觉得应该是在getInputSream()这里出错了。数据库的字段没有问题。rn听说这样的输入流不是“干净”的,还要选出来过.......rn麻烦这方面也解释一下。rnrn[color=#FF0000]报的错是:[/color]rn是插入出问题了 err2com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.connector.CoyoteInputStream@888e6c)' at line 1 论坛

servlet上传文件无法解析 pageContext

05-24

index.htmrnrnrnrn 文件上传rn rnrnrnrn rn  文件名称: rn  rn rn 上传路径:rn  rn rn  附加内容:rn  rn rn  rn rn rn rnrnrnrnrnrnFileup.java*******************************************************rnpackage judge;rnimport java.io.IOException;rnimport java.io.PrintWriter;import javax.servlet.ServletConfig;rnimport javax.servlet.ServletException;rnimport javax.servlet.http.HttpServlet;rnimport javax.servlet.http.HttpServletRequest;rnimport javax.servlet.http.HttpServletResponse;rnimport javax.servlet.jsp.*;rnrnimport com.jspsmart.upload.*;rnrnpublic class Fileup extends HttpServlet rn private ServletConfig config;rn public void doPost(HttpServletRequest request, HttpServletResponse response)rn throws ServletException, IOException rn response.setContentType("text/html;charset=gb2312");rn PrintWriter out = response.getWriter();rn SmartUpload su= new SmartUpload();rn su.initialize(config,request,response);rn int count=0;rn SmartUpload mySmartUpload = new SmartUpload();rn try rn mySmartUpload.initialize(config,request,response);rn mySmartUpload.upload();rn com.jspsmart.upload.File f1 = mySmartUpload.getFiles().getFile(0);rn String name = f1.getFileName(); rn count = mySmartUpload.save(mySmartUpload.getRequest().getParameter("PATH"));rn //other为form表单提交过来的rn String other=mySmartUpload.getRequest().getParameter("other"); //这里可以对other进行处理rn //request.getParameter("PATH");request.gerParameter("other");rn rn // 显示处理结果rn out.println(count + " file uploaded.");rnrn catch (Exception e)rn out.println("Unable to upload the file. ");rn out.println("Error : " + e.toString());rn rn rn out.println("");rn out.println("");rn rn rnrn rn rnrn错误内容****************************rn严重: Servlet.service() for servlet Fileup threw exceptionrnjava.lang.Error: 无法解析的编译问题:rn 无法解析 pageContextrnrn at judge.Fileup.doPost(Fileup.java:25)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)rn at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)rn at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)rn at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)rn at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)rn at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)rn at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:857)rn at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:565)rn at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1509)rn at java.lang.Thread.run(Thread.java:619) 论坛

jsp servlet 上传文件

05-10

直接servletrnrnimport java.io.File;rnimport java.io.IOException;rnimport java.util.List;rnrnimport javax.servlet.ServletException;rnimport javax.servlet.http.HttpServlet;rnimport javax.servlet.http.HttpServletRequest;rnimport javax.servlet.http.HttpServletResponse;rnrnimport org.apache.commons.fileupload.FileItem;rnimport org.apache.commons.fileupload.FileUploadException;rnimport org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;rnimport org.apache.commons.fileupload.disk.DiskFileItemFactory;rnimport org.apache.commons.fileupload.servlet.ServletFileUpload;rnrnpublic class FileUploadServlet extends HttpServlet rnrn private static final long serialVersionUID = 2827297299439162553L;rnrn public void doGet(HttpServletRequest request, HttpServletResponse response)rn throws ServletException, IOException rn //使用同一种处理方法rn doPost(request, response);rn rnrn public void doPost(HttpServletRequest request, HttpServletResponse response)rn throws ServletException, IOException rn request.setCharacterEncoding("UTF-8");rn response.setContentType("text/html; charset=UTF-8");rnrn //保存路径rn String savePath = getServletContext().getRealPath("/upload");rn File saveDir = new File(savePath);rn // 如果目录不存在,就创建目录rn if(!saveDir.exists())rn saveDir.mkdir();rn rnrn // 创建文件上传核心类rn DiskFileItemFactory factory = new DiskFileItemFactory();rn ServletFileUpload sfu = new ServletFileUpload(factory);rn //设置编码rn sfu.setHeaderEncoding("UTF-8");rn // 设置上传的单个文件的最大字节数为2Mrn sfu.setFileSizeMax(1024*1024*2);rn //设置整个表单的最大字节数为10Mrn sfu.setSizeMax(1024*1024*10);rnrn tryrn // 处理表单请求rn List itemList = sfu.parseRequest(request);rn for (FileItem fileItem : itemList) rn // 对应表单中的控件的namern String fieldName = fileItem.getFieldName();rn System.out.println("控件名称:" + fieldName);rn // 如果是普通表单控件rn if(fileItem.isFormField())rn String value = fileItem.getString();rn //重新编码,解决乱码rn value = new String(value.getBytes("ISO-8859-1"),"UTF-8");rn System.out.println("普通内容:" + fieldName + "=" + value);rn // 上传文件rn elsern // 获得文件大小rn Long size = fileItem.getSize();rn // 获得文件名rn String fileName = fileItem.getName();rn System.out.println("文件名:"+fileName+"\t大小:" + size + "byte");rnrn //设置不允许上传的文件格式rn if(fileName.endsWith(".exe"))rn request.setAttribute("msg", "不允许上传的类型!");rn elsern //将文件保存到指定的路径rn File file = new File(savePath,fileName);rn fileItem.write(file);rn request.setAttribute("msg", "上传成功!");rn rn rn rn catch(FileSizeLimitExceededException e)rn request.setAttribute("msg", "文件太大");rn catch(FileUploadException e)rn e.printStackTrace();rn catch(Exception e)rn e.printStackTrace();rn rn //上传完毕后 转发到首页rn request.getRequestDispatcher("/index.jsp").forward(request, response);rn rnrnrnrnrn错误信息:rn五月 10, 2015 11:07:44 上午 org.apache.catalina.core.StandardWrapperValve invokern严重: Servlet.service() for servlet [fileupload] in context with path [] threw exception [Servlet execution threw an exception] with root causernjava.lang.ClassNotFoundException: javax.servlet.ServletInputStreamrn at java.net.URLClassLoader$1.run(URLClassLoader.java:366)rn at java.net.URLClassLoader$1.run(URLClassLoader.java:355)rn at java.security.AccessController.doPrivileged(Native Method)rn at java.net.URLClassLoader.findClass(URLClassLoader.java:354)rn at java.lang.ClassLoader.loadClass(ClassLoader.java:425)rn at java.lang.ClassLoader.loadClass(ClassLoader.java:358)rn at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:115)rn at servlet.FileUploadServlet.doPost(FileUploadServlet.java:56)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)rn at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)rn at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:96)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)rn at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)rn at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)rn at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)rn at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)rn at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)rn at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)rn at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)rn at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)rn at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)rn at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)rn at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2462)rn at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2451)rn at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)rn at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)rn at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)rn at java.lang.Thread.run(Thread.java:745)rnrnrn不管用什么方法 都是这一句报错rn List itemList = sfu.parseRequest(request); 论坛

没有更多推荐了,返回首页