zoukankan      html  css  js  c++  java
  • 文件上传

    1.导入两个jar包

    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

    2.表单的属性设置和使用File控件选择文件

     <form enctype="multipart/form-data" action="test.jsp" method="post">
        姓名:<input type="text" name="username">
        选择图片:<input type="file" name="myfile">
        <input type="submit" value="提交">
        </form>

    from标签上的method的属性必须取值为post,不能取值get

    文件上传页面,代码所示:

    复制代码
    复制代码
    <%@page import="java.io.File"%>
    <%@page import="org.apache.commons.fileupload.FileItem"%>
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
    <%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>
    <%
       request.setCharacterEncoding("utf-8");
       boolean flag=ServletFileUpload.isMultipartContent(request);
       if(flag){
           DiskFileItemFactory factory=new DiskFileItemFactory();
           ServletFileUpload upload=new ServletFileUpload(factory);
          List<FileItem> fileList= upload.parseRequest(request);
          Iterator<FileItem> myitor= fileList.iterator();
          while(myitor.hasNext()){
              FileItem item=myitor.next();
              if(item!=null){
                  if(item.isFormField()){
                      String name=item.getFieldName();
                      if(name.equals("username")){
                          out.print(item.getString("utf-8"));
                      }
                  }else{
                     String fileName= item.getName();
                     String path="/WEB-INF/upload/";
                     String abosolutePath= this.getServletContext().getRealPath(path);
                     File file=new File(fileName);
                     File uploadFile=new File(abosolutePath,file.getName());
                     item.write(uploadFile);
                     out.print("上传成功");
                     
                  }
              }
          }
       }
    %>
    复制代码
    复制代码

    web界面:

  • 相关阅读:
    别人好的资源路径
    是否为微信浏览器,苹果安卓判断
    iframe滚动条置顶
    hadoop之MapReduce WordCount分析
    CentOS FTP服务器权限控制
    linux之sed用法
    hdfs-over-ftp安装与配置
    mysql grant all privileges on
    Notepad++快捷键大全
    coconHashMap实现原理分析
  • 原文地址:https://www.cnblogs.com/WuXuanKun/p/5639430.html
Copyright © 2011-2022 走看看