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对象。
UploadExample.jsp<%@ page contentType="text/html;charset=gb2312"%> <html><title><%= application.getServerInfo() %></title><body>上传文件程序应用示例<form action="doUpload.jsp" method="post"enctype="multipart/form-data"><%-- 类型enctype用multipart/form-data,这样可以把文件中的数据作为流式数据上传,不管是什么文件类型,均可上传。
--%>请选择要上传的文件<input type="file" name="upfile" size="50"><input type="submit" value="提交"></form></body></html>doUpload.jsp<%@ page contentType="text/html; charset=GBK" %> <%@ page import="java.io.*"%><%@ page import="java.util.*"%><%@ page import="javax.servlet.*"%><%@ page import="javax.servlet.http.*"%><html><head><title>upFile</title></head><body bgcolor="#ffffff"><%//定义上载文件的最大字节int MAX_SIZE = 102400 * 102400;// 创建根路径的保存变量String rootPath;//声明文件读入类DataInputStream in = null;FileOutputStream fileOut = null;//取得客户端的网络地址String remoteAddr = request.getRemoteAddr();//获得服务器的名字String serverName = request.getServerName();//取得互联网程序的绝对地址String realPath = request.getRealPath(serverName);realPath =realPath.substring(0,stIndexOf("\\"));//创建文件的保存目录rootPath = realPath + "\\upload\\";//取得客户端上传的数据类型String contentType = request.getContentType();try{if(contentType.indexOf("multipart/form-data") >= 0){ //读入上传的数据in = new DataInputStream(request.getInputStream()); int formDataLength = request.getContentLength();if(formDataLength > MAX_SIZE){out.println("<P>上传的文件字节数不可以超过" + MAX_SIZE + "</p>");return;}//保存上传文件的数据byte dataBytes[] = new byte[formDataLength];int byteRead = 0;int totalBytesRead = 0;//上传的数据保存在byte数组while(totalBytesRead < formDataLength){byteRead =in.read(dataBytes,totalBytesRead,formDataLength); totalBytesRead += byteRead;}//根据byte数组创建字符串String file = new String(dataBytes);//out.println(file);//取得上传的数据的文件名String saveFile =file.substring(file.indexOf("filename=\"") + 10); saveFile = saveFile.substring(0,saveFile.indexOf("\n")); saveFile = saveFile.substring(stIndexOf("\\") + 1,saveFile.indexOf("\""));int lastIndex = stIndexOf("=");//取得数据的分隔字符串String boundary = contentType.substring(lastIndex + 1,contentType.length());//创建保存路径的文件名String fileName = rootPath + saveFile;//out.print(fileName);int pos;pos = file.indexOf("filename=\"");pos = file.indexOf("\n",pos) + 1;pos = file.indexOf("\n",pos) + 1;pos = file.indexOf("\n",pos) + 1;int boundaryLocation = file.indexOf(boundary,pos) - 4; //out.println(boundaryLocation);//取得文件数据的开始的位置int startPos = ((file.substring(0,pos)).getBytes()).length; //out.println(startPos);//取得文件数据的结束的位置int endPos =((file.substring(0,boundaryLocation)).getBytes()).length; //out.println(endPos);//检查上载文件是否存在File checkFile = new File(fileName);if(checkFile.exists()){out.println("<p>" + saveFile + "文件已经存在.</p>"); }//检查上载文件的目录是否存在File fileDir = new File(rootPath);if(!fileDir.exists()){fileDir.mkdirs();}//创建文件的写出类fileOut = new FileOutputStream(fileName);//保存文件的数据fileOut.write(dataBytes,startPos,(endPos - startPos)); fileOut.close();out.println(saveFile + "文件成功上载.</p>");}else{String content = request.getContentType();out.println("<p>上传的数据类型不是multipart/form-data</p>");}}catch(Exception ex){throw new ServletException(ex.getMessage());}%></body></html>。
jsp用户上传头像、上传图片、邮件上传附件代码jsp教程用户上传头像、上传图片、邮件上传附件代码2. 页面表单的实现文件上传表单和普通表单有两个区别1) 需要文件上传字段<input type=”file” />2) form 表单的 enctype 属性需要指定为 multipart/form-data3. 服务器端解析request在 Servlet 中通过 request.getInputStream 获得表单上传数据,会发现数据是分段发送的由于自己写程序解析有难度,我们可以使用Apache 开发的开源组件Commons-fileupload需要导入 jar 包Commons-fileupload 和Commons-io4 . UploadServlet 中处理文件上传程序// 1. 创建工厂类DiskFileItemFactory factory = new DiskFileItemFactory();// 2. 创建FileUpload对象ServletFileUpload upload = new ServletFileUpload(factory);// 3. 判断是否是上传表单boolean b = upload.isMultipartContent(request);if(!b) {// 不是文件上传request.setAttribute("message", "对不起,不是文件上传表单!");request.getRequestDispatcher("/message.jsp").forward(requ est, response);return;}// 是文件上传表单// 4. 解析request,获得FileItem项List<FileItem> fileitems = upload.parseRequest(request); // 5. 遍历集合for(FileItem item : fileitems) {// 判断是不是普通字段if(item.isFormField()) {String name = item.getFieldName();String value = item.getString();// 手工的转换了value = new String(value.getBytes("iso-8859-1"),"utf-8"); System.out.println(name + "=" + value);} else {// 文件上传字段// 获得文件名String filename = item.getName();System.out.println(filename);filename = filename.substring(stIndexOf("")+1);System.out.println(filename);// 创建文件ServletContext context = getServletContext();String dir = context.getRealPath("WEN-INF/upload");File file = new File(dir, filename);file.createNewFile();// 获得流,读取数据写入文件InputStream in = item.getInputStream(); FileOutputStream fos = new FileOutputStream(file);int len;byte[] buffer = new byte[1024];while((len=in.read(buffer))>0)fos.write(buffer,0,len);fos.close();in.close();item.delete(); // 删除临时文件}二、文件上传处理细节1. 中文乱码问题1) 文件名中文乱码问题,解决办法:告诉文件上传组件以什么编码方式来解码文件名ServletUpload.setCharacterEncoding(“utf-8”);request. setCharacterEncoding(“utf-8”);2) 普通字段中文乱码问题fileitem.getString(“utf-8”);2. 临时文件对于大文件不能缓存在内存,需要缓存到硬盘,为了方便管理,我们需要设置临时文件存放目录// 设置临时文件的存放位置factory.setRepository(new File("d:/temp"));文件上传完毕需要删除临时文件,否则会导致服务器存在两份上传文件// 注意,需要先将流进行关闭,否则会导致临时文件无法删除out.close();in.close();// 删除临时文件fileitem.delete();3. 文件存放目录1) 目录需要隐藏,禁止外界直接访问2) 文件名需要保证不重复3) 文件应该分目录存放三、上传进度条1. 实现进度监听需要实现对文件上传进度的监听,需要给FileUpload 对象添加ProgressListener在upload方法中对与进度相关的数据进行处理upload.setProgressListener(new ProgressListener() {long num = 0;public void update(long bytesRead, long contentLength, int items) {long progress = bytesRead*100/contentLength;if(progress==num)return;num = progress;System.out.println("上传进度:" + progress + "%");// request.getSession().setAttribute("progress", progress);}});2. 在 jsp 页面显示进度实验:1) 使用 iframe 发送请求,请求一个Servlet, 在Servlet 中返回响应,发送自增的num此时会发现 iframe 会不停第想Servlet发送请求2) 点击文件上传按钮后,iframe立刻停止刷新,直至上传完毕页面跳转至新页面3)为了观察实验结果,将form 的target 指定为iframe,UploadServlet回送上传完毕的结果4) 出现上述问题的原因,浏览器不支持多线程同时访问服务器只能同时发送一个请求,这样的访问方式为同步访问5) 要在文件上传的同时在iframe中实现进度访问,就需要ie浏览器与服务器进行异步交互此时就需要 XMLHttpRequest 对象在网页特效中可以直接使用XMLHttpRequest 对象与服务器进行异步通信获得XmlHttpRequest 对象的方式有两种ie7以上版本var xhr = null;if(window.XMLHttpRequest)xhr = new XMLHttpRequest();ie7以下版本if(window.ActiveXObject)xhr = new ActiveXObject(“Microsoft.XMLHTTP”);获得对象后需要调用open方法输入请求地址注意请求方式,地址的输入,并且需要设置为true 指定异步访问该地址xhr.open(“get”,”/upload/servlet/UploadServlet”, false)// 调用send 方法发送请求,post方式需要发送消息体,get方式则不用直接传入null值xhr.send(null);// 访问 responseT ext 属性获得 Servlet 回送的数据document.write(xhr.responseText);四、 api方法1. DiskFileItemFactory 对象设置缓冲区大小,字节为单位,默认为10K,一般不用修改factory.setSizeThreshold(1000);设置临时文件存放目录factory.setRepository(file);2. ServletFileUpload 对象判断是否为文件上传表单boolean b = upload.isMultipartContent(request);解析request对象List<FileItem> list = upload.parseRequest(request);设置上传文件的最大值setFileSizeMax(long fileSizeMax)设置上传文件总量的最大值setSizeMax(long sizeMax)设置编码格式setHeaderEncoding(ng.String encoding)注册进度监听器setProgressListener(ProgressListener pListener)3. FileItem 对象获得表单字段的属性名item.getFieldName();获得普通字段的值item.getString(charsetName)获得文件上传字段的文件名item.getName()获得文件上传的流item.getInputStream()文件上传时需要注意的问题:1.如何设置上传文件最大值,并实现超出最大值时给用户一个友好提示upload.setFileSizeMax(1024*10); //设置最大值实现超出最大值时给用户一个友好提示:在程序中捕获FileUploadBase.FileSizeLimitExceededException只要程序抛出这个异常,代表用户上传的文件超出最大值2.上传过程中的乱码问题2.1 普通输入项的乱码item.getString("码表 ")2.2 上传文件名的乱码ServletFileUpload.setHeaderEncoding("码表")3.上传文件的安全性问题为防止用户直接上传文件,危害服务器安全,程序应禁止用户直接访问上传文件(即把上传文件保存在用户无法直接访问的目录)4.防止文件覆盖(UUID)5.文件打散存储(一个目录下面不能存超出1000个文件)用hash算法生成目录保存6.设置监听器,监听文件上传进度upload.setProgressListener(newProgressListener(){public void update(long arg0, longarg1, int arg2) {System.out.println("当前已上传" +arg0 + ",当前处理的文件总大小" + arg1);}});7.临时文件的删除问题处理完每一个文件上传后,一定要记得调用Fileitem.delete方法,删除临时文件8.限定上传文件类型判断上传文件后缀名。