zoukankan      html  css  js  c++  java
  • 使用Servlet实现上传文件功能

    1.servlet只需加上一个注释和用request.getPart来获取文件的值,这是servlet3.0的API

    2.表单需要加上一个属性enctype="multipart/form-data"

    现在附上代码

    表单:

     <form method="POST" action="upload" enctype="multipart/form-data" >
                File:
                <input type="file" name="file" id="file" /> <br/>
                Destination:
                <input type="text" value="f:" name="destination"/>
                <br/>
                <input type="submit" value="Upload" name="upload" id="upload" />
    </form>

    servlet:

    在类的声名上加上这两个注释

    @WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
    @MultipartConfig

    自定义的方法:

    processRequest方法是获取文件的值的

    protected void processRequest(HttpServletRequest request,
                HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
          request.setCharacterEncoding("utf-8");
          
         //获取路径 final String path = request.getParameter("destination");
         //获取文件的值
    final Part filePart = request.getPart("file"); System.out.println(filePart); final String fileName = getFileName(filePart);      //使用IO流对文件进行操作 OutputStream out = null; InputStream filecontent = null; final PrintWriter writer = response.getWriter(); try { out = new FileOutputStream(new File(path + File.separator + fileName)); filecontent = filePart.getInputStream(); int read; final byte[] bytes = new byte[1024]; while ((read = filecontent.read(bytes)) != -1) { out.write(bytes, 0, read); } writer.println("New file " + fileName + " created at " + path); LOGGER.log(Level.INFO, "File {0} being uploaded to {1}", new Object[]{fileName, path}); } catch (FileNotFoundException fne) { writer.println("You either did not specify a file to upload or are " + "trying to upload a file to a protected or nonexistent " + "location."); writer.println("<br/> ERROR: " + fne.getMessage()); LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}", new Object[]{fne.getMessage()}); } finally { if (out != null) { out.close(); } if (filecontent != null) { filecontent.close(); } if (writer != null) { writer.close(); } } }

    getFileName方法是获取文件名的

    private String getFileName(final Part part) {
    final String partHeader = part.getHeader("content-disposition");
    LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
    for (String content : part.getHeader("content-disposition").split(";")) {
    if (content.trim().startsWith("filename")) {
    return content.substring(
    content.indexOf('=') + 1).trim().replace(""", "");
    }
    }
    return null;
    }

    最后在doPost方法里写

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    }

    到这里就全部完成了,长传成功的效果,如图:

    路漫漫其修远兮,吾将上下而求索
  • 相关阅读:
    flume sink两种类型 file_rool 自定义sing com.mycomm.MySink even if there is only one event, the event has to be sent in an array
    为什么引入进程20年后,又引入线程?
    As of Flume 1.4.0, Avro is the default RPC protocol.
    Google Protocol Buffer 的使用和原理
    Log4j 2
    统一日志 统一订单
    网站行为跟踪 Website Activity Tracking Log Aggregation 日志聚合 In comparison to log-centric systems like Scribe or Flume
    Percolator
    友盟吴磊:移动大数据平台的架构、实践与数据增值
    Twitter的RPC框架Finagle简介
  • 原文地址:https://www.cnblogs.com/-brl/p/7296180.html
Copyright © 2011-2022 走看看