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);
                }
            }
            
        }
    }
    %>
  • 相关阅读:
    SpringMVC
    SpringMVC
    SpringMVC
    Spring
    Spring
    值类型和引用类型
    判断字符串的开头和结尾
    二分法(课后)
    验证码
    从1-36中随机出6个不相等的数
  • 原文地址:https://www.cnblogs.com/yangronglin/p/5639373.html
Copyright © 2011-2022 走看看