博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
FileUpload
阅读量:5099 次
发布时间:2019-06-13

本文共 6831 字,大约阅读时间需要 22 分钟。

一upload原理:

      1.表单的method必须是post方法

      2.enctype属性必须是“mutipatr/form-data”类型

       enctype默认的属性是“application/x-www-form-urlencoded”

       enctype的作用是:告知服务器请求正文的MIME类型

      application/x-www-form-urlencoded:username=aaa&password=123

      ServletRequest.getParameter(String name),该方法是专门用来读取enctype是“application/x-www-form-urlencoded”时的方法

      3.在Servlet里面通过request.getInputStream()方法就可以获得文件输入流

        byte[] b= new byte[1024];

        int len=0;

        InputStream is = request.getInputStream();

        while((len=is.read(b)) != -1){
        System.out.println(new String(b,0 ,len));
        }

代码示例

1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2     pageEncoding="UTF-8"%> 3  4  5  6 
7 Insert title here 8 9 10
11 请输入FileName
12
13
14 ${pageContext.request.contextPath}15 16 17 18 19
20 21 22
jspShow
1 package jcbc.ds.test1; 2  3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.util.List; 6  7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest;10 import javax.servlet.http.HttpServletResponse;11 12 import org.apache.commons.fileupload.FileItem;13 import org.apache.commons.fileupload.FileUploadException;14 import org.apache.commons.fileupload.disk.DiskFileItemFactory;15 import org.apache.commons.fileupload.servlet.ServletFileUpload;16 17 /**18  * Servlet implementation class UploadServlet19  */20 public class UploadServlet extends HttpServlet {21     private static final long serialVersionUID = 1L;22        23     /**24      * @see HttpServlet#HttpServlet()25      */26     public UploadServlet() {27         super();28         29     }30 31     /**32      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)33      */34     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {35         36         //创建DiskFileItemFactory对象37         //DiskFileItemFactory dis = new DiskFileItemFactory();38         //创建ServletFileUpload对象39         /*ServletFileUpload servletupload = new ServletFileUpload(dis);*/40         byte[] b= new byte[1024];41         int len=0;42         InputStream is = request.getInputStream();43         while((len=is.read(b)) != -1){44             System.out.println(new String(b,0 ,len));45         }46         /*try {47             List
fileItem = servletupload.parseRequest(request);48 for(FileItem items : fileItem) {49 System.out.println(items.getName());50 //进行解析传过来的数据进行封装51 }52 is.close();53 54 } catch (FileUploadException e) {55 // TODO Auto-generated catch block56 e.printStackTrace();57 }*/58 59 }60 61 }
ServerServlet

二借助第三方组件实现文件上传:

  步骤:

  1.拷贝jar包commons-fileupload.jar  commons-io.jar

    具体参考  

  2.//创建DiskFileItemFactory对象

    DiskFileItemFactory disfileitemfactory = new DiskFileItemFactory();

    //创建ServletFileUpload对象
    ServletFileUpload servletupload = new ServletFileUpload(disfileitemfactory);

  3.获取封装信息

    List<FileItem> fileItem = servletupload.parseRequest(request);//这里会抛异常

  具体步骤代码如下:

1 package jcbc.ds.test1; 2  3 import java.io.File; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.OutputStream; 7 import java.util.List; 8  9 import javax.servlet.ServletException;10 import javax.servlet.http.HttpServlet;11 import javax.servlet.http.HttpServletRequest;12 import javax.servlet.http.HttpServletResponse;13 14 import org.apache.commons.fileupload.FileItem;15 import org.apache.commons.fileupload.FileUploadException;16 import org.apache.commons.fileupload.disk.DiskFileItemFactory;17 import org.apache.commons.fileupload.servlet.ServletFileUpload;18 import org.apache.commons.io.FileUtils;19 20 /**21  * Servlet implementation class UploadServlet22  */23 public class UploadServlet extends HttpServlet {24     private static final long serialVersionUID = 1L;25        26     /**27      * @see HttpServlet#HttpServlet()28      */29     public UploadServlet() {30         super();31         32     }33 34     /**35      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)36      */37     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {38         response.setContentType("text/html; charset=gbk");39         //创建DiskFileItemFactory对象40         DiskFileItemFactory disfileitemfactory = new DiskFileItemFactory();41         //创建ServletFileUpload对象42         ServletFileUpload servletupload = new ServletFileUpload(disfileitemfactory);43         44         try {45             //封装46             List
fileItem = servletupload.parseRequest(request);47 for(FileItem files : fileItem ){48 if(files.isFormField()){49 System.out.println(files.getFieldName());50 }51 else{52 InputStream is = files.getInputStream();53 String name = files.getName();54 //截取文件名55 String fileName = name.substring(name.lastIndexOf("\\")+1);56 System.out.println(fileName);//打印结果为huxuebing.txt57 58 System.out.println(request.getServletContext().getRealPath("/fileName"));59 //创建File类对象60 File file = new File(request.getServletContext().getRealPath("/")+fileName);61 //判断该文件是否存在如果不存在就创建,存在就不创建62 if(file.exists()==false){63 System.out.println("==================");64 file.createNewFile();65 System.out.println("==================");66 }67 try {68 //向创建的文件写入69 files.write(file);70 } catch (Exception e) {71 // TODO Auto-generated catch block72 e.printStackTrace();73 }74 75 }76 77 }78 79 } catch (FileUploadException e) {80 // TODO Auto-generated catch block81 e.printStackTrace();82 }83 84 }85 86 }
commontsUploadFiles
FileNamehuxuebing.txtD:\workSpace\web2\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\day18\fileName====================================
result

 

  

 

  

转载于:https://www.cnblogs.com/huxuebing/p/5861376.html

你可能感兴趣的文章
bzoj1044 [HAOI2008]木棍分割——前缀和优化DP
查看>>
使用 Override 和 New 关键字进行版本控制
查看>>
安装Ubuntu的那些事儿
查看>>
Safari导入书签
查看>>
HTML列表
查看>>
c#FTP应用---windows iis
查看>>
linux下调整java版本
查看>>
AutoCAD实用技巧基础篇
查看>>
Junit测试工具
查看>>
ubuntu 系统环境配置记录
查看>>
C# 流总结
查看>>
org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist: file:/input
查看>>
jumpserver安装与部署
查看>>
Apache,php配置
查看>>
Python特殊语法:filter、map、reduce、lambda
查看>>
vs2008 此安装不支持该项目类型
查看>>
C# Hash算法
查看>>
转:C语言深度剖析三
查看>>
HDU 2095 find your present (2) 异或
查看>>
swipe滚动失效
查看>>