JSP程序设计案例课件:文件上传和下载-发送邮件
- 格式:ppt
- 大小:553.00 KB
- 文档页数:35
用JSP实现拖拽上传文件和文件夹JSP(JavaServer Pages)是一种动态网页技术,允许将Java代码嵌入到HTML页面中。
拖拽上传文件和文件夹是一种常见的网页交互功能,可以使用JSP来实现。
在实现拖拽上传文件和文件夹功能之前,首先需要了解一下拖拽上传的基本原理。
在HTML中,可以通过Drag and Drop API来获取拖拽的文件和文件夹。
然后,可以使用JavaScript将拖拽的文件和文件夹发送到服务器端,服务器端可以使用JSP来处理这些文件和文件夹。
以下是一个基本的实现拖拽上传文件的JSP页面的示例:```htmlpageEncoding="UTF-8"%><!DOCTYPE html><html><head><meta charset="UTF-8"><title>拖拽上传文件</title><script>function handleDrop(event)event.preventDefault(; // 禁止浏览器打开文件var files = event.dataTransfer.files;//遍历上传的文件for (var i = 0; i < files.length; i++)var file = files[i];// 创建FormData对象,用于发送文件到服务器var formData = new FormData(;formData.append("file", file);// 创建一个XMLHttpRequest对象,发送文件到服务器var xhr = new XMLHttpRequest(;xhr.open("POST", "upload.jsp", true);xhr.onreadystatechange = functioif (xhr.readyState == 4 && xhr.status == 200)//上传成功console.log(xhr.responseText);}};xhr.send(formData);}}</script></head><body ondragover="event.preventDefault(;"ondrop="handleDrop(event);"><h1>拖拽上传文件</h1><p>将文件拖拽到此处上传</p></body></html>```当文件被拖拽到页面的时候,`handleDrop(`函数会被调用。
用JSP编写文件上传袁毅:2000-10-23如果你曾用VB编写文件上传的组件的话,那么用JAVA编写文件上传的JAVABEAN十分容易。
下面的例子只是一个简版package yuanyifileup;import java.io.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.jsp.PageContext;public class yuanyifileup{private ServletRequest request;private ServletResponse response;private ServletConfig config;ServletInputStream DATA;int FormSize;File f1;FileOutputStream os;DataInputStream is;String filename;byte[] b;byte t;boolean flag=false;public yuanyifileup(){ }public void initialize(ServletConfig config,HttpServletRequest request,HttpServlet Response response) throws IOException{this.request=request;this.response=response;this.config=config;DATA = request.getInputStream();FormSize=request.getContentLength();}public void initialize(PageContext pageContext) throws IOException{request=pageContext.getRequest();response=pageContext.getResponse();config=pageContext.getServletConfig();DATA = request.getInputStream();FormSize=request.getContentLength(); }public boolean setFilename(String s) {try{File f1=new File(s);os=new FileOutputStream(f1);}catch(IOException e){return(false);}return(true);}public void getByte(){int i=0;try{is=new DataInputStream(DATA);b=new byte[FormSize];while (true){try{t=is.readByte();b[i]=t;i++;}catch(EOFException e) { break;}}is.close();}catch(IOException e) {}}public boolean save() {int i=0,start1=0,start2=0; String temp="";if (!flag){getByte();flag=true;}try{temp=new String(b,"ISO8859_1");}catch(UnsupportedEncodingException e) {return(false);}start1=temp.indexOf("image/");temp=temp.substring(start1);start1=temp.indexOf("");temp=temp.substring(start1+4);start2=temp.indexOf(";");if (start2!=-1){temp=temp.substring(0,start2);}try{byte[] img=temp.getBytes("ISO8859_1");for (i=0;i<img.length;i++){ os.write(img[i]); }os.close();}catch(IOException e){return(false);}return(true);}如果有不明白的发E-Mail:yymailbox@.Bye }。
内容概要文件的上传必要的前提:a.表单的method 必须是post,get方式有长度限制b. 表单form的属性的enctype必须是multipart/from-data类型作用form的enctype属性和请求消息头”Content-Type”作用是一样的,告知服务器请求正文的类型启动Tomcat进行试验:文件上传的前提是以上的abc文件上传原理:案例演示创建页面index.jspaction交给处理创建文本文件a.txt结果是null nullServletRequest中有getInputStream和getReader所以以流的方式获取客户端的提交的数据有分页符请求正文的分析器,使用第三方的开源工具3使用第三方组件实现文件上传:用来解析请求正文commons 就是对基本类的封装,将一些代码进行重构后封装,使得使用更方便,使用工具的方式减少代码的书写量搭建环境:拷入jar包解析过程常用类的分析内存和虚拟内存,文件一般使用内存进行存储,但是会使用硬盘的空间进行存储文件名在工具jar包中的FAQ中文件的保存路径上传jsp页面修改路径限制用户的上传文件类型生成GUID的方法文件上传需要的数据库设计c 文件过多,检索耗时较多使用这种方式可以创建16*16个目录4e 限制上传文件的类型使用ie就可以自动识别浏览器的类型,即使被修改成了图片的扩展名,也不会上传文件,但是,火狐浏览器不能识别伪装了图片扩展名的文件,也会上传该文件解决办法:每个文件的头部都有对应的文件类型,获取到该头部的文件类型,然后进行判断。
限制上传文件的大小当文件超出的大小限制的时候需要抓捕异常,对异常进行处理设置总文件大小的限制临时文件的问题进度条问题:带进度条的文件上传文件下载Servlet规范中的监听器FrameDemo案例演示说明观察者设计模式服务器会注册监听器Spring容器当访问request.getSession的时候才会创建Session在访问index.jsp的时候会创建Session,因为jsp默认的Session是TRUE 使用Session监听器可以监听访问量需求分析定义User类定义list集合作为数据库创建登录页面创建登录Servlet创建默认主页User实现HttpSessionListener,实现其方法知识总结。
MyEclipse 6 实战开发讲解视频入门10 JSP 文件上传下载2007-12-2本视频讲解了如何使用最新版本开源的Apache Commons FileUpload 来上传文件以及如何编写文件下载代码.视频部分代码屏幕出现闪烁, 错位, 不便之处请参考本文中的源码和文档中绿色部分的注释:// Set factory constraintsfactory.setSizeThreshold(yourMaxMemorySize); // 设置最多只允许在内存中存储的数据,单位:字节factory.setRepository(yourTempDirectory); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录(默认可以不用设置)// Create a new file upload handlerServletFileUpload upload = new ServletFileUpload(factory);// Set overall request size constraint// 设置允许用户上传文件大小,单位:字节upload.setSizeMax(yourMaxRequestSize);友情提示: 下载微软网盘文件时关闭下载工具, 否则你将得到错误的文件, 双击EXE 会出来DOS 窗口. 正确操作是点击文件名后能看到显示下载链接和文件大小等信息.代码:/self.aspx/Public/MyEclipse6Videos/10 _JSPFileUploadDownload.zip132 KB视频: /self.aspx/Public/MyEclipse6Video s/myeclipse6_10.exe 16分31秒6.0 MB内容包括:1. Apache Commons FileUpload 项目介绍2. 下载并增加必要的类库3. 编写文件上传表单HTML4. 编写文件上传处理JSP5. 编写文件下载JSP6. 发布并测试视频截图:代码:<form name="f1" id="f1" action="upload.jsp" method="post" ENCTYPE="multipart/form-data"><table border="0"><tr><td>Login:</td><td><input type="text" name="login" id="login"></td></tr><tr><td>Password:</td><td><input type="password" name="password" id="password"></td></tr><tr><td valign="top">附件:<br></td><td valign="top"><input type="file" name="file" id="file"></td></tr>< <td colspan="2" align="center"><input type="submit"></td></tr></table></form>upload.jsp<%@ page language="java" import="java.util.*" pageEncoding="GBK"%><%@page import="mons.fileupload.servlet.ServletFileUpload"%><%@page import="mons.fileupload.disk.DiskFileItemFactory"%><%!/*** 得到文件的短路径, 不包括目录.* @date 2005-10-18** @param fileName* 需要处理的文件的名字.* @return the short version of the file's name.*/public static String getShortFileName(String fileName) {if (fileName != null) {String oldFileName = new String(fileName);fileName = fileName.replace('\\', '/');// Handle dirif (fileName.endsWith("/")) {int idx = fileName.indexOf('/');if (idx == -1 || idx == fileName.length() - 1) {return oldFileName;} else {return oldFileName.substring(idx + 1, fileName.length() - 1);}if (stIndexOf("/") > 0) {fileName = fileName.substring(stIndexOf("/") + 1,fileName.length());}return fileName;}return "";}%><%// Check that we have a file upload requestboolean isMultipart = ServletFileUpload.isMultipartContent(request);if (isMultipart) {// Create a factory for disk-based file itemsmons.fileupload.FileItemFactory factory = new DiskFileItemFactory();// Create a new file upload handlerServletFileUpload upload = new ServletFileUpload(factory);// Parse the requestList /* FileItem */items = upload.parseRequest(request);// Process the uploaded itemsIterator iter = items.iterator();while (iter.hasNext()) {mons.fileupload.FileItem item = (mons.fileupload.FileItem) iter .next();if (item.isFormField()) {String name = item.getFieldName();String value = item.getString("GBK");out.println(name + "=" + value);} else {String fieldName = item.getFieldName();//fileString fileName = item.getName();String contentType = item.getContentType();boolean isInMemory = item.isInMemory();long sizeInBytes = item.getSize();out.println("上传的文件名是:" + fileName);if (fileName == null || fileName.length() == 0) {out.println("请选择一个文件来上传");} else {java.io.FileOutputStream fout = new java.io.FileOutputStream(application.getRealPath("upload/"+ getShortFileName(fileName)));fout.write(item.get());fout.close();}}}} else {out.println("请用文件上传表单来访问这个页面");}%>相关资料:下载地址/fileupload//io/用法文档:/fileupload/using.htmlUsing FileUploadFileUpload can be used in a number of different ways, depending upon the requirements of your application. In the simplest case, you will call a single method to parse the servlet request, and then process the list of items as they apply to your application. At the other end of the scale, you might decide to customize FileUpload to take full control of the way in which individual items are stored; for example, you might decide to stream the content into a database.Here, we will describe the basic principles of FileUpload, and illustrate some of the simpler - and most common - usage patterns. Customization of FileUpload is described elsewhere.FileUpload depends on Commons IO, so make sure you have the version mentioned on the dependencies page in your classpath before continuing.How it worksA file upload request comprises an ordered list of items that are encoded according to RFC 1867, "Form-based File Upload in HTML". FileUpload can parse such a request and provide your application with a list of the individual uploaded items. Each such item implements the FileItem interface, regardless of its underlying implementation.This page describes the traditional API of the commons fileupload library. The traditional API is a convenient approach. However, for ultimate performance, you might prefer the faster Streaming API.Each file item has a number of properties that might be of interest for your application. For example, every item has a name and a content type, and can provide an InputStream to access its data. On the other hand, you may need to process items differently, depending upon whether the item is a regular form field - that is, the data came from an ordinary text box or similar HTML field - or an uploaded file. The FileItem interface provides the methods to make such a determination, and to access the data in the most appropriate manner.FileUpload creates new file items using a FileItemFactory. This is what gives FileUpload most of its flexibility. The factory has ultimate control over how each item is created. The factory implementation that currently ships with FileUpload stores the item's data in memory or on disk, depending on the size of the item (i.e. bytes of data). However, this behavior can be customized to suit your application.Servlets and PortletsStarting with version 1.1, FileUpload supports file upload requests in both servlet and portlet environments. The usage is almost identical in the two environments, so the remainder of this document refers only to the servlet environment.If you are building a portlet application, the following are the two distinctions you should make as you read this document:∙Where you see references to the ServletFileUpload class, substitute the PortletFileUpload class.∙Where you see references to the HttpServletRequest class, substitute the ActionRequest class.Parsing the requestBefore you can work with the uploaded items, of course, you need to parse the request itself. Ensuring that the request is actually a file upload request is straightforward, but FileUpload makes it simplicity itself, by providing a static method to do just that.// Check that we have a file upload requestboolean isMultipart = ServletFileUpload.isMultipartContent(request); Now we are ready to parse the request into its constituent items.The simplest caseThe simplest usage scenario is the following:∙Uploaded items should be retained in memory as long as they are reasonably small.∙Larger items should be written to a temporary file on disk.∙Very large upload requests should not be permitted.∙The built-in defaults for the maximum size of an item to be retained in memory, the maximum permitted size of an upload request, and the location oftemporary files are acceptable.Handling a request in this scenario couldn't be much simpler:// Create a factory for disk-based file itemsFileItemFactory factory = new DiskFileItemFactory();// Create a new file upload handlerServletFileUpload upload = new ServletFileUpload(factory);// Parse the requestList /* FileItem */ items = upload.parseRequest(request);That's all that's needed. Really!The result of the parse is a List of file items, each of which implements the FileItem interface. Processing these items is discussed below.Exercising more controlIf your usage scenario is close to the simplest case, described above, but you need a little more control, you can easily customize the behavior of the upload handler or the file item factory or both. The following example shows several configuration options:// Create a factory for disk-based file itemsDiskFileItemFactory factory = new DiskFileItemFactory();// Set factory constraintsfactory.setSizeThreshold(yourMaxMemorySize); // 设置最多只允许在内存中存储的数据,单位:字节factory.setRepository(yourTempDirectory); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录(默认可以不用设置)// Create a new file upload handlerServletFileUpload upload = new ServletFileUpload(factory);// Set overall request size constraint// 设置允许用户上传文件大小,单位:字节upload.setSizeMax(yourMaxRequestSize);// Parse the requestList /* FileItem */ items = upload.parseRequest(request);Of course, each of the configuration methods is independent of the others, but if you want to configure the factory all at once, you can do that with an alternative constructor, like this:// Create a factory for disk-based file itemsDiskFileItemFactory factory = new DiskFileItemFactory(yourMaxMemorySize, yourTempDirectory);Should you need further control over the parsing of the request, such as storing the items elsewhere - for example, in a database - you will need to look into customizing FileUpload.Processing the uploaded itemsOnce the parse has completed, you will have a List of file items that you need to process. In most cases, you will want to handle file uploads differently from regular form fields, so you might process the list like this:// Process the uploaded itemsIterator iter = items.iterator();while (iter.hasNext()) {FileItem item = (FileItem) iter.next();if (item.isFormField()) {processFormField(item);} else {processUploadedFile(item);}}For a regular form field, you will most likely be interested only in the name of the item, and its String value. As you might expect, accessing these is very simple.// Process a regular form fieldif (item.isFormField()) {String name = item.getFieldName();String value = item.getString();...}For a file upload, there are several different things you might want to know before you process the content. Here is an example of some of the methods you might be interested in.// Process a file uploadif (!item.isFormField()) {String fieldName = item.getFieldName();String fileName = item.getName();String contentType = item.getContentType();boolean isInMemory = item.isInMemory();long sizeInBytes = item.getSize();...}With uploaded files, you generally will not want to access them via memory, unless they are small, or unless you have no other alternative. Rather, you will want to process the content as a stream, or write the entire file to its ultimate location. FileUpload provides simple means of accomplishing both of these.// Process a file uploadif (writeToFile) {File uploadedFile = new File(...);item.write(uploadedFile);} else {InputStream uploadedStream = item.getInputStream();...uploadedStream.close();}Note that, in the default implementation of FileUpload, write() will attempt to rename the file to the specified destination, if the data is already in a temporary file. Actually copying the data is only done if the the rename fails, for some reason, or if the data was in memory.If you do need to access the uploaded data in memory, you need simply call the get() method to obtain the data as an array of bytes.// Process a file upload in memorybyte[] data = item.get();...Resource cleanupThis section applies only, if you are using the DiskFileItem. In other words, it applies, if your uploaded files are written to temporary files before processing them.Such temporary files are deleted automatically, if they are no longer used (more precisely, if the corresponding instance of java.io.File is garbage collected. This is done silently by an instance of mons.io.FileCleaningTracker, which starts a reaper thread.In what follows, we assume that you are writing a web application. In a web application, resource cleanup is controlled by an instance ofjavax.servlet.ServletContextListener. In other environments, similar ideas must be applied.The FileCleanerCleanupYour web application should use an instance ofmons.fileupload.FileCleanerCleanup. That's very easy, you've simply got to add it to your web.xml:<web-app>...<listener><listener-class>mons.fileupload.servlet.FileCleanerCleanup</listener-class></listener>...</web-app>Creating a DiskFileItemFactoryThe FileCleanerCleanup provides an instance ofmons.io.FileCleaningTracker. This instance must be used when creating a mons.fileupload.disk.DiskFileItemFactory. This should be done by calling a method like the following:public static DiskFileItemFactorynewDiskFileItemFactory(ServletContext context,File repository) {FileCleaningTracker fileCleaningTracker= FileCleanerCleanup.getFileCleaningTracker(context);return new DiskFileItemFactory(fileCleaningTracker,DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD,repository);}Disabling cleanup of temporary filesTo disable tracking of temporary files, you may set the FileCleaningTracker to null. Consequently, created files will no longer be tracked. In particular, they will no longer be deleted automatically.Interaction with virus scannersVirus scanners running on the same system as the web container can cause some unexpected behaviours for applications using FileUpload. This section describes some of the behaviours that you might encounter, and provides some ideas for how to handle them.The default implementation of FileUpload will cause uploaded items above a certain size threshold to be written to disk. As soon as such a file is closed, any virus scanner on the system will wake up and inspect it, and potentially quarantine the file - that is, move it to a special location where it will not cause problems. This, of course, will be a surprise to the application developer, since the uploaded file item will no longer be available for processing. On the other hand, uploaded items below that same threshold will be held in memory, and therefore will not be seen by virus scanners. This allows for the possibility of a virus being retained in some form (although if it is ever written to disk, the virus scanner would locate and inspect it).One commonly used solution is to set aside one directory on the system into which all uploaded files will be placed, and to configure the virus scanner to ignore that directory. This ensures that files will not be ripped out from under the application, but then leaves responsibility for virus scanning up to the application developer. Scanning the uploaded files for viruses can then be performed by an external process, which might move clean or cleaned files to an "approved" location, or by integrating a virus scanner within the application itself. The details of configuring an external process or integrating virus scanning into an application are outside the scope of this document.Watching progressIf you expect really large file uploads, then it would be nice to report to your users, how much is already received. Even HTML pages allow to implement a progress bar by returning a multipart/replace response, or something like that.Watching the upload progress may be done by supplying a progress listener://Create a progress listenerProgressListener progressListener = new ProgressListener(){public void update(long pBytesRead, long pContentLength, int pItems) {System.out.println("We are currently reading item " + pItems);if (pContentLength == -1) {System.out.println("So far, " + pBytesRead + " bytes have been read.");} else {System.out.println("So far, " + pBytesRead + " of " + pContentLength+ " bytes have been read.");}}};upload.setProgressListener(progressListener);Do yourself a favour and implement your first progress listener just like the above, because it shows you a pitfall: The progress listener is called quite frequently. Depending on the servlet engine and other environment factory, it may be called for any network packet! In other words, your progress listener may become a performance problem! A typical solution might be, to reduce the progress listeners activity. For example, you might emit a message only, if the number of megabytes has changed://Create a progress listenerProgressListener progressListener = new ProgressListener(){private long megaBytes = -1;public void update(long pBytesRead, long pContentLength, int pItems) {long mBytes = pBytesRead / 1000000;if (megaBytes == mBytes) {return;}megaBytes = mBytes;System.out.println("We are currently reading item " + pItems);if (pContentLength == -1) {System.out.println("So far, " + pBytesRead + " bytes have been read.");} else {System.out.println("So far, " + pBytesRead + " of " + pContentLength+ " bytes have been read.");}}};What's nextHopefully this page has provided you with a good idea of how to use FileUpload in your own applications. For more detail on the methods introduced here, as well as other available methods, you should refer to the JavaDocs.The usage described here should satisfy a large majority of file upload needs. However, should you have more complex requirements, FileUpload should still be able to help you, with it's flexible customization capabilities.。
1 JSP文件上传简单实例1、index.html代码:<html><head><title>上传图片</title></head><body><form action="do_upload.jsp" method="post" enctype="multipart/form-data"><input type="file" name="Photo"><input type="submit" value="上传"></form></body></html>2、使用到的函数和类说明File类文件和目录路径名的抽象表示形式,File(parent,child)方法根据parent 抽象路径名和child 路径名字符串创建一个新File实例FileOutputStream文件输出流,InputStream输入流,将输入数据看成一根管道,可以形象的将输入流比喻成管道的入口,而输出流比喻成管道的出口。
read(byte[] b) 从此输入流中将最多 b.length 个字节的数据读入一个字节数组中。
read() 从此输入流中读取一个数据字节。
write(int b) 将指定字节写入此文件输出流,write(byte[] b, int off, int len) 将指定字节数组中从偏移量off 开始的len 个字节写入此文件输出流。
write(byte[] b) 将 b.length 个字节从指定字节数组写入此文件输出流中Random.readLine()逐行读入,Random.seek(int pos)设置到此文件开头测量到的文件指针偏移量,该位置发生下一个读取和写入操作,Random.getFilePointer()返回此文件当前偏移量,Random.readByte()此方法从该文件的当前文件指针开始读取第一个字节。
Jsp页面实现文件上传下载第1 页jsp页面实现文件上传代码开发的过程见用TOMCAT作简单的jsp web开发名称:jsp页面上传类作者:SinNeRMail:vogoals[at]特点:1可以多文件上传;2返回上传后的文件名;3form表单中的其他参数也可以得到。
先贴上传类,JspFileUploadpackage com.vogoal.util;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.Hashtable;import javax.servlet.ServletInputStream;import javax.servlet.http.HttpServletRequest;/** vogoalAPI 1.0*************************** by *mail:********************//*** JSP上传文件类** @author SinNeR* @version 1.0*/public class JspFileUpload {/** request对象*/private HttpServletRequest request = null;/** 上传文件的路径*/private String uploadPath = null;/** 每次读取得字节的大小*/private static int BUFSIZE = 1024 * 8;/** 存储参数的Hashtable */private Hashtable paramHt = new Hasptable();/** 存储上传的文件的文件名的ArrayList */private ArrayList updFileArr = new ArrayList();/*** 设定request对象。