Life is long ......

继续向前 永不停止

   :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 

实现文件上传,表单属性需要设置为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  阅读(37707)  评论(2编辑  收藏  举报