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界面:

     
  • 相关阅读:
    java-继承的注意事项
    java-代码块-局部代码块、构造代码块、静态代码块
    java-源文件中可以有多个类,但是最多只能有一个public修饰
    java-权限修饰符的区别
    APP测试-adb简介
    APP测试-Android模拟器
    APP测试-SDK环境 for Windows
    自动化测试-流程
    接口测试-接口请求关联
    接口测试-moco+excel+requests框架
  • 原文地址:https://www.cnblogs.com/hr1997/p/5638416.html
Copyright © 2011-2022 走看看