JSP程序设计案例课件:文件上传和下载-发送邮件

合集下载

用JSP实现拖拽上传文件和文件夹

用JSP实现拖拽上传文件和文件夹

用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编写文件上传

用JSP编写文件上传

用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 }。

课件ppt怎么发送

课件ppt怎么发送

发送后的注意事项
04
保存发送记录
保存发送邮件的记录
01
在发送PPT课件后,建议将发送邮件的记录保存在本地,以便后
续核对和查询。
记录发送时间
02
记录下邮件发送的具体时间,以便在需要时核对。
记录收件人信息
03
确保记录下收件人的邮箱地址、姓名等信息,以便后续跟进和
确认。
检查收件人是否收到文件
01
02
发送PPT的技巧
03
添加注释和说明
添加必要的注释和说明
提供背景信息
在PPT中加入注释和说明,帮助收件 人更好地理解内容,包括重要概念、 数据和图表等。
如果PPT涉及到某些专业术语或背景 知识,可以在PPT中提供相关背景信 息,帮助收件人更好地理解内容。
突出关键信息
使用不同的字体、颜色和大小来突出 PPT中的关键信息,使收件人更容易 关注到重要内容。
提醒收件人查看附件
提醒收件人查看附件
在邮件中明确提醒收件人查看附件中的PPT,确保他们不会错过重 要信息。
提供附件的简要说明
在邮件中简要说明附件的内容和重要性,以便收件人更好地了解 PPT的重要性和用途。
确保附件格式正确
确保PPT的格式正确,易于打开和查看,避免出现格式错误或乱码等 问题。
及时跟进收件人反馈
优化PPT文件质量
在调整文件格式时,可以调整PPT文件的分辨率、颜色和字 体等参数,以优化文件质量并减小文件大小。
压缩PPT文件
• 使用压缩软件减小文件大小:如果PPT文件较大,可以使用压缩软件对其进行压缩,以减小文件大小,方便传输和存储。请 选择可靠的压缩软件,并确保在压缩过程中不会损坏PPT文件。
及时跟进收件人反馈

JSP Web应用开发案例教程课件第四章

JSP Web应用开发案例教程课件第四章
【实例4-2】 本实例使用request常用方法 getParameter(String s)获取用户提交的数字信息,并对其进 行运算后输出。
实例代码如下:
4.1 request对象
15
4.1.3 使用request对象获取用户提交的信息
<%@page contentType="text/html;charset=gb2312"%>
A request对象 B response对象 C out对象 D application对象 E session对象
5
4.1 request对象
4.1 request对象
6
4.1.1 request对象的常用方法
在JSP中,内置对象request封装了用户提交到服务器端的数据,调用该对象的相关方 法可以获取封装的信息。request对象的常用方法有很多,下面简单介绍一下。
4.1 request对象
13
4.1.2 request对象的应用
程序运行效果如图4-1所示。
图4-1 使用request对象获取的信息
4.1 request对象
14
4.1.3 使用request对象获取用户提交的信息
使用request对象获取用户信息最常用的 方法是getParameter(String s),下面通 过实例简单介绍。
while(enu.hasMoreElements()){ String Name = (String)enu.nextElement(); String value = (String)request.getParameter(Name);
} %>
</body> </html>

day20文件上传和下载

day20文件上传和下载

内容概要文件的上传必要的前提: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.JSP.文件上传下载

MyEclipse.JSP.文件上传下载

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.。

JSP2.0应用教程_13 Web开发常用功能

JSP2.0应用教程_13 Web开发常用功能

• 编写JavaBean
2013-9-1
18
13.3.2 Web查询实例
– 在Web应用myMail的WEBINF\classes\myGoogle目录下,创建 JavaBean的具体实现类GoogleBean
2013-9-1
12
13.2.3 文件上传实例
• 编写Web应用配置文件
– 在Web应用myFileUpload的WEB-INF目录 下,创建Web应用配置文件web.xml
• 编写Servlet
– 在Web应用myFileUpload的WEBINF\classes\myFileUpload目录下,创建 Servlet的具体实现类UploadServlet
2013-9-1
11
13.2.3 文件上传实例
• 建立Web应用框架
– 在Tomcat安装目录下的webapps下创建 Web应用目录myFileUpload,将cos.jar文 件复制到myFileUpload目录的WEBINF\lib目录下
• 编写页面
– 在Web应用的myFileUpload目录下,创建 用户请求的文件上传HTML页面
10
13.2.2 文件上传处理的实现包
• 目前有多种实现服务器端处理文件上传 功能的Java实现 • 本节使用O’Reilly公司提供的开源的文件 上传API包来实现文件上传对应的文件为 cos-05Nov2002.zip • 将文件解压缩,在lib子目录下的cos.jar 就是具体实现服务器端处理文件上传的 JAR包
Web开发常用功能
主要内容
• • • • • 13.1 电子邮件 13.2 文件上传 13.3 Web搜索 本章小结 习题
2013-9-12 Nhomakorabea13.1 电子邮件

jsp实现文件上传和下载

jsp实现文件上传和下载

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()此方法从该文件的当前文件指针开始读取第一个字节。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

• 完成文件上传和下载的方法有很多种,比如:jspsmart公 司的jspSmartUpload组件,O`Rrilly公司的cos组件, Jakarta Apache公司的commonsFileUpload组件, JavaZoom的uploadbean组件,以及Struts组件中自带的 org.apache.struts.upload类工具等等。
课外拓展
1.进一步熟悉jspSmartUpload组件概述
• jspSmartUpload组件实现文件上传和下载功能,具有以下特 点: (1)使用简单。 (2)能全程控制上传. (3)能对上传的文件在大小、类型等方面做出限制。 (4)下载灵活. (5) 能将文件上传到数据库中,也能将数据库中的数据下载下 来.
• jspSmartUpload 的安装与配置步骤如下 : (1)下载jspSmartUpload组件后,将其解压。 (2)将其中的com目录复制到应用程序目录下的WEBINF\classes中(如:chap09\WEB-INF\classes)即可,该应 用程序即可使用jspSmartUpload组件。 (3)如果希望tomcat服务器的所有web应用程序都可使用 jspSmartUpload组件,将com目录复制到 webapps\ROOT\WEB-INF\classes文件夹中即可。 (4)重新启动tomcat,就可以在jsp文件中使用 jspSmartUpload组件。
• request类的功能等同于JSP内置的对象request。之所以提供 这个类,是因为对于文件上传表单,通过request对象无法获 得表单项的值,必须通过jspSmartUpload组件提供的request 对象来获取。request类提供的主要方法见图9-4。
• smartupload类完成文件的上传和下载工作。smartupload类 提供的主要方法见表9-5。
使用环境。
(2)编写一个应用jspSmartUpload组件上传 Easy_Buy电子商城中商品图片的程序。 (3)参照本书说明,配置好JavaMail组件的使用环 境。 (4)编写一个应用JavaMail组件发送Easy_Buy电子 商城中会员订单的程序。
本课小结
1. jspSmartUpload组件中常用的类和方法 2. JavaMail发送电子邮件的方法
本课目标
运用jspSmartUpload组件实现文件的上传 和下载 运用JavaMail类来发送邮件 。
技能 目标
素质 目标
严谨认真的工作态度 语言表达和与人沟通能力 团队合作精神
教学情境--引入新课
情境展示 1. 163网站网盘上传,演示邮件发送功能 。
教师示范与讲解--1
案例分析 任务一:使用jspSmartUpload组件实现文件上传。
• jspSmartUpload常用类
file类包装了一个上传文件的所有信息。通过file类,可 以得到上传文件的文件名、文件大小、扩展名、文件数据等 信息。file类提供的主要方法见图9-2。
• files类表示所有上传文件的集合,通过files类可以得到上 传文件的数目、大小等信息。files类提供的主要方法见图 9-3。
主要内容
•本课目标 •新课引入与项目展示 •案例1 –文件上传 •案例2 –文件下载 •案例3 –发送邮件 •课堂实践 •巩固与提高
本课目标
知识 目标
掌握jspSmartUpload组件中常用的类和方法 掌握在JSP中应用jspSmartUpload组件实现上传和下载 的方法(重点、难点) 掌握JavaMail中常用的类和方法 (重点、难点)
• 通常使用Properties 来创建一个Session 对象,基本语句 格式如下: Session sendMailSession; sendMailSession = Session.getInstance(props, null); Transport类 • Transport 类是用来发送信息,而Store类用来接收信息。 基本语句格式如下: Transport transport; transport = sendMailSession.getTransport("smtp");
课堂演示9.1 使用 jspSmartUpload 组件实现文件上传。 upload.html 提 供 文 件 上 传 表 单 , do_upload.jsp完成文件上传。
• 演示结果
学生模仿--1
任务一:学生模仿完成课堂演示9.1中的内容
教师示范与讲解--2
案例分析 任务一:使用jspSmartUpload组件实现文件下载 。
课堂演示9.2
使 用 jspSmartUpload 组 件 实 现 文 件 下 载 。 download.html 提 供 文 件 下 载 表 单 , do_download.jsp完成文件下载。
• 演示结果
学生模仿--2
任务一:学生模仿完成课堂演示9.2中的内容。
教师示范与讲解--3
案例分析 任务一:使用JavaMail发送电子邮件。
Properties类 • Properties类用来创建一个Session对象。Properties类寻找 字符串“mail.smtp.host”,该属性值就是发送邮件的主机, 基本语句格式如下: Properties props = new Properties (); props.put("mail.smtp.host", ""); Session类 • Session类代表JavaMail 中的一个邮件Session,每一个基 于 JavaMail的应用程序至少有一个Session,也可以有任意 多的Session。
课堂演示9.3
使用 JavaMail 发送电子邮件。 mailto.html 提供 书写邮件表单, sendmail.jsp 完成邮件的发送。
• 演示结果
学生模仿--3
任务一:学生模仿完成课堂演示9.3中的内容
课堂实践
实践要求 【课堂实践9-1】 (1)参照本书说明,配置好jspSmartUpload组件的
Message类 Message对象将存储实际发送的电子邮件信息,Message对 象被作为一个MimeMessage对象来创建并且需要知道应当 选择哪一个JavaMail session。基本语句格式如下: Message newMessage = new MimeMessage(sendMailSession);
发送邮件
• JavaMail概述 JavaMail是Sun发布的处理电子邮件的应用程序接口,它预 置了一些最常用的邮件传送协议的实现方法,并且提供了很 容易的方法去调用它们. • JavaMail的安装和配置步骤如下 : (1)将下载的压缩文件解压到指定文件夹。 (2)将JavaMail包解压后的mail.jar文件和JAF包中 jaractivation.jar复制到应用程序文件夹下的WEB-INF\lib文件 夹中。 (3)重启服务器,JavaMail便可以正常使用了。
相关文档
最新文档