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

    首先到引入两个jar包,分别是

    commons-fileupload-1.3.1.jar
    commons-io-2.4.jar

    index.jsp

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

    test.jsp

    <%
    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()){
                    //证明是普通表单字段 返回表单字段的name属性值
                    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 absolutePath =this.getServletContext().getRealPath(path);
                File file =new File(filename);
                File uploadFile =new File(absolutePath,file.getName());
                    item.write(uploadFile);
                    out.print("上传成功!"+filename);
                }
            }
            
        }
    }
    %>

    完成!

  • 相关阅读:
    tensorflow模型的保存与恢复
    Anaconda Linux端环境管理
    Windows环境下Redis集群部署
    Error fetching https://ruby.taobao.org/:RubySass淘宝镜源无效解决
    ORM 轻量级框架 Dapper(介绍)
    TypeScript 数据类型
    TypeScript 环境搭建
    微信小程序反编译
    利用Fiddler实现手机抓包
    SQL 优化常用查询
  • 原文地址:https://www.cnblogs.com/myhome-1/p/5638528.html
Copyright © 2011-2022 走看看