Servlet 上传文件

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/twilight_karl/article/details/69917866

更改form的enctype属性

enctype属性默认是application/x-www-form-urlencoded,发送文件时需要更改为multipart/form-data

<form action=”/File/Photo” method=”post” enctype=”multipart/form-data”>

发送一个图片时的http请求如下:

POST /File/Photo HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
X-HttpWatch-RID: 90747-10177
Referer: http://localhost:8080/File/photo.html
Accept-Language: zh-CN
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Content-Type: multipart/form-data; boundary=---------------------------7e179f4038a
Accept-Encoding: gzip, deflate
Host: localhost:8080
Content-Length: 566814
DNT: 1
Connection: Keep-Alive
Cache-Control: no-cache

-----------------------------7e179f4038a
Content-Disposition: form-data; name="file"; filename="D:\鍥剧墖\Camera Roll\b.jpg"
Content-Type: image/jpeg

表单如下:

   <form action="/File/Photo_Stream" method="post" enctype="multipart/form-data">
    <input type="file" name='file' /><br/>
    <input type="submit" value="提交" />
   </form>

使用Part对象接受文件

Part对象也可以获取http头部信息
part.getHeader(“name”) :获取头部信息中name对应的值
part.write(fileName) : 将part对象写入到文件中,文件的路径在 @MultipartConfig中配置

getHeader(“Content-Disposition”)的结果是:

form-data; name=”file”; filename=”D:\鍥剧墖\Camera Roll\b.jpg”
因此可以根据Content-Disposition属性的值获取文件的名称

getPart(name)

Part对象不需要通过构造函数创建,可以通过req.getPart()方法返回对应的文件对象

        Part part = req.getPart("file");
        // 获取文件名
        String header = part.getHeader("Content-Disposition");
        String fileName = header.substring(header.indexOf("filename=\"")+10,header.length()-1);
        fileName = fileName.substring(3);
        // 写入到文件
        part.write(fileName);

getParts()

getParts() 返回所有的文件对象,返回类型是Collection集合。需要遍历集合才能处理所有文件

        Collection<Part> part = req.getParts();
        for(Part temp :part){
            String header = temp.getHeader("Content-Disposition");
            // 获取文件名
            String fileName = header.substring(header.indexOf("filename=\"")+10,header.length()-1);
            output.println("<br/>Content-Disposition:"+header);
            output.println("<br/>fileName:"+fileName);
            fileName = fileName.substring(3);
            // 写入到文件
            temp.write(fileName);
        }

@MultipartConfig

Tomcat中必须标注@MultipartConfig才能使用 Part

@MultipartConfig可以设置上传文件的相关信息:

  1. fileSizeThreshold : 上传文件大小的门槛
  2. location : 配置文件的保存位置
  3. maxRequestSize : 设置请求个数,默认值为-1L,表示不限个数
// 表示上传的文件在write()时保存到E盘
@MultipartConfig(location="E:/")

也可以在web.xml中配置@MultipartConfig

    <servlet>
        <servlet-name>Photo</servlet-name>
        <servlet-class>Files.Photo</servlet-class>
        <multipart-config>
            <location>E:/</location>
        </multipart-config>
    </servlet>

    <servlet-mapping>
        <servlet-name>Photo</servlet-name>
        <url-pattern>/Photo</url-pattern>
    </servlet-mapping>

使用Part的InputStream

可以使用Part的getInputStream()方法返回一个输入流,再使用传统的方式将输入流输出到文件

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        // 获取part对象
        Part part = req.getPart("file");

        // 获取输入流
        InputStream data = part.getInputStream();
        byte [] temp = new byte [1024];

        FileOutputStream output = new FileOutputStream(new File("E:/s.jpg"));
        int len = 0 ;
        while(-1 != (len = data.read(temp))){
            output.write(temp, 0, len);
        }
        output.flush();
        output.close();
    }

参考:
JonnyWei的专栏

展开阅读全文

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); 论坛

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