惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
Jina AI
Jina AI
雷峰网
雷峰网
Blog — PlanetScale
Blog — PlanetScale
Hugging Face - Blog
Hugging Face - Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Last Week in AI
Last Week in AI
博客园 - 司徒正美
罗磊的独立博客
J
Java Code Geeks
Engineering at Meta
Engineering at Meta
WordPress大学
WordPress大学
Vercel News
Vercel News
A
About on SuperTechFans
I
InfoQ
D
DataBreaches.Net
爱范儿
爱范儿
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
U
Unit 42
aimingoo的专栏
aimingoo的专栏
宝玉的分享
宝玉的分享
P
Proofpoint News Feed
Microsoft Azure Blog
Microsoft Azure Blog
美团技术团队

博客园 - patrickwai

java enum用法 Java中哈希表(Hashtable)是如何实现的 注意for循环中变量的作用域 用SAX Parser(Simple API for XML)分析RSS android权限 【转】分治法求最大值最小值 JPA实体关系映射 JPA基本实体映射学习 Servlet学习(一) 用javascript与正则表达式验证表单 - patrickwai - 博客园 java题目分析 java中的synchronized Spring学习——依赖注入 Spring学习——Hello World xml,javascript,XMLHttpRequest 学习笔记 向依赖关系宣战——依赖倒置、控制反转和依赖注入辨析[转载] MySql存储过程学习 自己用C语言写的扫雷算法 移位运算实际应用——判断整数N是否为2的阶次方
Servlet实现基本文件上传
patrickwai · 2010-09-28 · via 博客园 - patrickwai

实现文件上传,表单属性需要设置为method=”post”,encType=multipart/form-data,在服务器端通过request.getInputStream()获得文件输入流,然后对流进行操作,获得所需要的内容。

Html页面代码upload.html

<form action="UploadServlet3" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" name="upload"value="上传">
</form>

1.实现基本文件上传

Servlet代码

public class UploadServlet1 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOException {

           InputStream in = request.getInputStream();
           File f = new File("d:/temp","aaa.txt");
           FileOutputStream fos = new FileOutputStream(f);

           byte[] b = new byte[1024];
           int n=0;

           while((n=in.read(b))!=-1){
              fos.write(b,0,n);
           }

           fos.close();
           in.close();

    }

}

此方法上传的文件打开后如下:

-----------------------------26962244645705

Content-Disposition: form-data; name="file";filename="a.txt"

Content-Type: text/plain

Java Servlet Technology

As soon as the web began to be used for deliveringservices, service providers recognized the need for dynamic content. Applets,one of the earliest attempts toward this goal, focused on using the clientplatform to deliver dynamic user experiences. At the same time, developers alsoinvestigated using the server platform for this purpose. Initially, CommonGateway Interface (CGI) scripts were the main technology used to generatedynamic content. Although widely used, CGI scripting technology has a number ofshortcomings, including platform dependence and lack of scalability. To addressthese limitations, Java Servlet technology was created as a portable way toprovide dynamic, user-oriented content.

-----------------------------26962244645705

Content-Disposition: form-data; name="upload"

上传

-----------------------------26962244645705--

此处有一个回车符

前面4行和后面6行是表单的一些属性,是默认加入的。

2.出去文件流中的多余内容(只支持ie)

UploadServlet2

public class UploadServlet2 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String tempFileName = (String) request.getSession().getId();
		// create the tempfile.
		File temp = new File("d:/temp", tempFileName);
		FileOutputStream o = new FileOutputStream(temp);
		if (request.getContentLength() > 297) {
			// write theupload content to the temp file.
			InputStream in = request.getInputStream();
			byte b[] = new byte[1024];
			int n;
			while ((n = in.read(b)) != -1) {
				o.write(b, 0, n);
			}
			o.close();
			in.close();
			// read the tempfile.
			RandomAccessFile random = new RandomAccessFile(temp, "r");
			// read Line2 tofind the name of the upload file.
			int second = 1;
			String secondLine = null;
			while (second <= 2) {
				secondLine = random.readLine();
				second++;
			}

			// get the lastlocation of the dir char.'\\'.
			int position = secondLine.lastIndexOf('\\');
			// get the nameof the upload file.
			String fileName = secondLine.substring(position + 1,
					secondLine.length() - 1);
			// relocate tothe head of file.
			random.seek(0);
			// get thelocation of the char.'Enter' in Line4.
			long forthEndPosition = 0;
			int forth = 1;
			while ((n = random.readByte()) != -1 && (forth <= 4)) {
				if (n == '\n') {
					forthEndPosition = random.getFilePointer();
					forth++;
				}
			}
			File realFile = new File("d:/temp", fileName);
			RandomAccessFile random2 = new RandomAccessFile(realFile, "rw");
			// locate the endposition of the content.Count backwards 6 lines.
			random.seek(random.length());
			long endPosition = random.getFilePointer();
			long mark = endPosition;
			int j = 1;
			while ((mark >= 0) && (j <= 6)) {
				mark--;
				random.seek(mark);
				n = random.readByte();
				if (n == '\n') {
					endPosition = random.getFilePointer();
					j++;
				}
			}
			// locate to thebegin of content.Count for 4 lines's end position.
			random.seek(forthEndPosition);
			long startPoint = random.getFilePointer();
			// read the realcontent and write it to the realFile.
			while (startPoint < endPosition - 1) {
				n = random.readByte();
				random2.write(n);
				startPoint = random.getFilePointer();
			}
			random2.close();
			random.close();
			// delete the tempfile.
			temp.delete();
			System.out.println("File uploadsuccess!");
		} else {
			System.out.println("Nofile!");
		}

	}

}

posted on 2010-09-28 11:07  patrickwai  阅读(37781)  评论()    收藏  举报