文件上传简介

来源:互联网 发布:迪优美特网络机顶盒 编辑:程序博客网 时间:2024/06/11 18:44

文件上传的核心点

1:用<input type=”file”/> 来声明一个文件域。File:_____ <浏览>.
2:必须要使用post方式的表单。
3:必须设置表单的类型为multipart/form-data.是设置这个表单传递的不是key=value值。传递的是字节码.

对于一个普通的表单来说只要它是post类型。默认就是

Content-type:application/x-www-from-urlencoded
表现形式
1:在request的请求头中出现。
2:在form声明时设置一个类型enctype="application/x-www-form-urlencoded";
如果要实现文件上传,必须设置enctype=“multipart/form-data”

表单与请求的对应关系:



4、如何获取上传的文件的内容-以下是自己手工解析txt文档


/** * 如果一个表单的类型是post且enctype为multipart/form-date * 则所有数据都是以二进制的方式向服务器上传递。 * 所以req.getParameter("xxx")永远为null。 * 只可以通过req.getInputStream()来获取数据,获取正文的数据 *  * @author wangjianme * */public class UpServlet extends HttpServlet {public void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {req.setCharacterEncoding("UTF-8");String txt = req.getParameter("txt");//返回的是nullSystem.err.println("txt is :"+txt);System.err.println("=========================================");InputStream in = req.getInputStream();//byte[] b= new byte[1024];//int len = 0;//while((len=in.read(b))!=-1){//String s = new String(b,0,len);//System.err.print(s);//}BufferedReader br = new BufferedReader(new InputStreamReader(in));String firstLine = br.readLine();//读取第一行,且第一行是分隔符号String fileName = br.readLine();fileName = fileName.substring(fileName.lastIndexOf("\\")+1);// bafasd.txt"fileName = fileName.substring(0,fileName.length()-1);br.readLine();br.readLine();String data = null;//获取当前项目的运行路径String projectPath = getServletContext().getRealPath("/up");PrintWriter out  = new PrintWriter(projectPath+"/"+fileName);while((data=br.readLine())!=null){if(data.equals(firstLine+"--")){break;}out.println(data);}out.close();}}















0 0