`
高级java工程师
  • 浏览: 405279 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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);

    }

}


经过测试,完全可以实现,希望与大家分享......................
分享到:
评论

相关推荐

    用JSPServlet实现文件上传.rar

    【摘要】:该文介绍了在B/S模式下,通过JSP/Servlet技术实现文件上传的方法。 文件上传在很多网站应用中是必不可少的,在电子商务中上传商品图片,在音乐网站中上传流行歌曲……一个高效率的文件上传功能尤为重要。...

    北大青鸟6.0课件S2使用JSP/Servlet/Ajax技术开发新闻发布系统2

    北大青鸟6.0课件S2使用JSP/Servlet/Ajax技术开发新闻发布系统2,,我只能上传小于50M的文件,所以分了2次上传,下载使用JSP/Servlet/Ajax技术开发新闻发布系统1后就是全部的了。如有问题加Q:329139513.注明来意

    JSP/servlet实现上传下载

    以上就是使用JSP和Servlet实现文件上传下载的基本流程和关键代码。在实际应用中,我们还需要考虑错误处理、安全性(如防止文件覆盖、上传恶意文件等)以及性能优化(如使用缓冲、断点续传等)。在大型项目中,可能还...

    jsp/servlet文件上传(带进度)

    本篇将详细介绍`JSP/servlet`实现文件上传,并结合`AJAXFileUpload`工具进行进度显示,提供更友好的用户体验。 首先,`JSP`是一种基于Java的服务器端脚本语言,它允许在HTML页面中嵌入Java代码,使得动态生成网页变...

    jsp+servlet实现文件上传下载

    ### jsp+servlet实现文件上传下载 在现代Web开发中,文件上传下载是常见的功能之一。JSP(JavaServer Pages)与Servlet技术结合可以轻松实现这一功能。本篇将详细介绍如何利用jspSmartUpload组件实现文件的上传与...

    jsp/servlet技术实现动态网站-后台

    至于`project`这个压缩包文件,很可能是项目源代码的打包,其中可能包含了`jsp`页面、`servlet`类、相关的JavaBean(用于封装数据)、配置文件(如web.xml)、以及可能使用的第三方库。解压后,开发人员可以通过阅读...

    jsp+servlet实现大型文件下载

    本教程将深入讲解如何利用JSP和Servlet来实现大型文件的下载功能,这对于构建高效、稳定的Web应用至关重要。 一、Servlet简介 Servlet是Java平台上的一个标准接口,用于扩展服务器的功能。在Web开发中,Servlet通常...

    基于 JSP/Servlet 的头像设置功能实现

    2. `UploadServlet.java`:这个Servlet可能是处理文件上传的,接收AJAX请求,处理文件并更新用户头像信息。 3. `Ajax.js`:这是一个JavaScript文件,实现了AJAX请求的逻辑,向服务器发送文件并处理返回的结果。 4. ...

    jsp+servlet实现文件上传和下载

    总结来说,通过JSP和Servlet,结合`commons-fileupload`与`commons-io`库,我们可以构建一个功能完善的文件上传和下载系统,同时需要注意安全性、性能和用户体验。在实际开发中,还可以结合其他框架如Spring MVC,...

    JSP+Servlet实现文件上传到服务器功能

    本文实例为大家分享了JSP+Servlet实现文件上传到服务器功能的具体代码,供大家参考,具体内容如下 项目目录结构大致如下: 正如我在上图红线画的三个东西:Dao、service、servlet 这三层是主要的结构,类似 MVC ...

    纯jsp+servlet版的多文件上传与下载

    总结,这个项目展示了如何在传统的Java Web环境中使用JSP和Servlet实现文件上传和下载功能,同时利用Apache Commons FileUpload库简化了文件上传的复杂性。对于初学者,这是一个很好的实践案例,能够深入理解MVC模式...

    jsp&servlet; 实现文件上传

    Jcreator pro开发工具。需要导入的common和servlet-api.jar包...上传文件页面,选择文件。提交后转到 servlet服务器。 /FileUpload 处理上传文件。显示文件名称,和上传后路径。things文件夹作为存储上传文件文件夹。

    hibernate jsp/servlet +AJAX的文档管理系统(毕业设计)

    - **Servlet处理逻辑**:编写Servlet来处理用户的HTTP请求,如登录验证、文件上传、搜索请求等,通过调用Hibernate方法与数据库交互。 - **JSP页面**:JSP页面用于展示数据和接收用户输入,结合EL(Expression ...

    jsp,servlet上传下载文件

    文件上传下载是 Web 应用中的一种常见需求,使用 jsp 页面和 servlet 实现文件上传下载是其中的一种解决方案。下面将详细介绍 jsp、servlet 文件上传下载技术。 文件上传下载原理 文件上传下载的原理是将客户端的...

    servlet jsp javabean 实现的文件上传

    综上所述,Servlet、JSP和JavaBean协同工作,实现了用户友好的文件上传功能。Servlet处理HTTP请求,JSP提供用户界面,JavaBean封装业务逻辑,共同构建了一个安全、可控的文件上传系统。通过合理的代码组织和优化,...

    使用JSP/Servlet/Ajax技术开发新闻发布系统

    完成开发后,新闻发布系统会被打包成WAR文件,然后部署到Web服务器上,如将WAR文件上传至Tomcat的webapps目录下,启动服务器即可对外提供服务。 总结,"使用JSP/Servlet/Ajax技术开发新闻发布系统"涉及到的技术栈...

    jsp与servlet 上传文件 javaBean上传文件

    本篇文章将深入探讨如何使用JSP与Servlet进行文件上传,并特别关注如何解决中文文件名乱码的问题。 首先,我们需要理解文件上传的基本流程。当用户在JSP页面上选择文件并提交表单时,JSP会将文件数据封装到HTTP请求...

    jsp+servlet+mysql实现文件上传功能

    在本文中,我们将深入探讨如何使用JSP、Servlet和MySQL实现文件上传功能,特别是基于Servlet 3.0的实现方式。文件上传是Web应用程序中常见的需求,它允许用户上传文件到服务器并存储在数据库中。这里我们将讲解关键...

    jsp结合servlet实现文件上传

    本知识点主要聚焦于如何利用JSP和Servlet实现文件上传功能,这是一个在Web应用中非常实用的功能,例如用户在网站上提交简历、上传图片等。 首先,我们需要了解文件上传的基本原理。HTTP协议本身不支持文件上传,但...

    JSP中(jsp+servlet)实现的文件上传

    通过以上步骤,你将在Glassfish v2服务器上实现一个基本的JSP+Servlet文件上传功能,只允许上传.gif和.jpg格式的图片,同时阻止.exe和.bat等可能带有恶意代码的文件。这样的功能在实际应用中非常实用,如用户头像...

Global site tag (gtag.js) - Google Analytics