Jsp/Servlet:实现文件上传与下载

1.客户端上传文件

客户端通过一个Jsp页面,上传文件到服务器,该Jsp页面必须含有File类表单,并且表单必须设置enctype="multipart/form-data"。提交表单时通过内置对象request,request.getInputStream();方法获得一个输入流。

在上传文件时,会有附加信息,如下所示:
-----------------------------7d71042a40328

Content-Disposition: form-data; name="fileforload"; filename="C:\Documents and Settings\ZJ\桌面\book.txt"

Content-Type: text/plain

//此处为文件内容

-----------------------------7d71042a40328

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



commit

-----------------------------7d71042a40328--


附加信息大小为297字节(不确定这个值,测试得到),可通过request.getContentLength()>297来判断是否上传了文件还是提交空字符串。

2.测试

fileupload.jsp负责提交文件,accept.jsp负责实现上传功能。

fileupload.jsp

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=GB18030">

<title>This page for FileUpload</title>

</head>

<body>

<p>Choose the file for uploading:

<form action="accept.jsp" method=post enctype="multipart/form-data">

<input type=file name=fileforload size=30>

<br>

<input type=submit value=commit name=submit>

</form>

</body>

</html>


accept.jsp

<html>

<head>

<%@ page language="java" import="java.io.*" %>

<meta http-equiv="Content-Type" content="text/html; charset=GB18030">

<title>The real file</title>

</head>

<body>

<%try{

//use sessionid to create a temp file.

String tempFileName=(String)session.getId();

//create the temp file.

File temp=new File("d:/temp",tempFileName);

FileOutputStream o=new FileOutputStream(temp);

if(request.getContentLength()>297){

//write the upload 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 temp file.

RandomAccessFile random=new RandomAccessFile(temp,"r");

//read Line2 to find the name of the upload file.

int second=1;

String secondLine=null;

while(second<=2){

secondLine=random.readLine();

second++;

}

//get the last location of the dir char.'\\'.

int position=secondLine.lastIndexOf('\\');

//get the name of the upload file.

String fileName=secondLine.substring(position+1,secondLine.length()-1);

//relocate to the head of file.

random.seek(0);

//get the location 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 end position 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 the begin of content.Count for 4 lines's end position.

random.seek(forthEndPosition);

long startPoint=random.getFilePointer();

//read the real content 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 temp file.

temp.delete();

out.print("File upload success!");

}

else{

out.print("No file!");

}

}

catch(IOException e){

out.print("upload error.");

e.printStackTrace();

}

%>

</body>

</html>


下载,采用servlet

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<servlet>

<servlet-name>LoadFileServlet</servlet-name>

<servlet-class>com.zj.sample.LoadFile</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>LoadFileServlet</servlet-name>

<url-pattern>/loadFile</url-pattern>

</servlet-mapping>
</web-app>

download.jsp做测试

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=GB18030">

<title>download page</title>

</head>

<body>

<a href=loadFile>Download:test.zip</a>

</body>

</html>


写servlet
package com.zj.sample;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.OutputStream;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;



public class LoadFile extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException {

OutputStream o = response.getOutputStream();

byte b[] = new byte[1024];

// the file to download.


File fileLoad = new File("d:/temp", "test.rar");


// the dialogbox of download file.

response.setHeader("Content-disposition", "attachment;filename="

+ "test.rar");

// set the MIME type.

response.setContentType("application/x-tar");

// get the file length.

long fileLength = fileLoad.length();

String length = String.valueOf(fileLength);

response.setHeader("Content_Length", length);

// download the file.

FileInputStream in = new FileInputStream(fileLoad);

int n = 0;

while ((n = in.read(b)) != -1) {

o.write(b, 0, n);

}

}



public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

doGet(request, response);

}

}


经过测试,完全可以实现,希望与大家分享......................
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
本代码主要应用的是jsp技术,而实现文件功能,这个功能也是比较常见的,也是比较常用的,更是在网络中比较流行的。 技术为创建显示动态生成内容的Web页面提供了一个简捷而快速的方法。JSP技术的设计目的是使得构造基于Web的应用程序更加容易和快捷,而这些应用程序能够与各种Web服务器,应用服务器,浏览器和开发工具共同工作。 Web应用开发的JavaServer Pages技术方法 在开发JSP规范的过程中,太阳微系统公司(Sun Microsystems Inc.)与许许多多主要的Web服务器、应用服务器和开发工具供应商,以及各种各样富有经验的开发团体进行合作。其结果是找到了一种为应用和页面开发人员平衡了可移植性和易用性的开发方法。 JSP技术在多个方面加速了动态Web页面的开发: 将内容的生成和显示进行分离 使用JSP技术,Web页面开发人员可以使用HTML或者XML标识来设计和格式化最终页面。使用JSP标识或者小脚本来生成页面上的动态内容(内容是根据请求来变化的,例如请求帐户信息或者特定的一瓶酒的价格)。生成内容的逻辑被封装在标识和JavaBeans组件中,并且捆绑在小脚本中,所有的脚本在服务器端运行。如果核心逻辑被封装在标识和Beans中,那么其他人,如Web管理人员和页面设计者,能够编辑和使用JSP页面,而不影响内容的生成。 在服务器端,JSP引擎解释JSP标识和小脚本,生成所请求的内容(例如,通过访问JavaBeans组件,使用JDBCTM技术访问数据库,或者包含文件),并且将结果以HTML(或者XML)页面的形式发送回浏览器。这有助于作者保护自己的代码,而又保证任何基于HTML的Web浏览器的完全可用性。 强调可重用的组件 绝大多数JSP页面依赖于可重用的,跨平台的组件(JavaBeans或者Enterprise JavaBeansTM组件)来执行应用程序所要求的更为复杂的处理。开发人员能够共享和交换执行普通操作的组件,或者使得这些组件为更多的使用者或者客户团体所使用。基于组件的方法加速了总体开发过程,并且使得各种组织在他们现有的技能和优化结果的开发努力中得到平衡。 采用标识简化页面开发 Web页面开发人员不会都是熟悉脚本语言的编程人员。JavaServer Page技术封装了许多功能,这些功能是在易用的、与JSP相关的XML标识中进行动态内容生成所需要的。标准的JSP标识能够访问和实例化JavaBeans组件,设置或者检索组件属性,下载Applet,以及执行用其他方法更难于编码和耗时的功能。 通过开发定制化标识库,JSP技术是可以扩展的。今后,第三方开发人员和其他人员可以为常用功能创建自己的标识库。这使得Web页面开发人员能够使用熟悉的工具和如同标识一样的执行特定功能的构件来工作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值