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下载文件的实现方法 及 注意
这样,就可以保证在用户点击下载链接的时候浏览器一定会弹出提示窗口来询问你是下载还是直接打开并允许你选择要打开的应用程序,除非你设置了浏览器的一些默认行为。
//application.getRealPath("/main/mvplayer/CapSetup.msi");获取的物理路径
String filedownload = "想办法找到要提供下载的文件的物理路径+文件名";
String filedisplay = "给用户提供的下载文件名";
{
in.close();
in = null;
}
//这里不能关闭
//if(outp != null)
//{
//outp.close();
//outp = null;
//}
}
%>
对于第二种方法,我认为应该是比较常用的。不过有几个地方是值得我们注意的:
java.io.OutputStream outp = null;
java.io.FileInputStream in = null;
try
{
outp = response.getOutputStream();
in = new FileInputStream(filenamedownload);
{
in.close();
in = null;
}
//这里不能关闭
jsp+servlet实现文件的下载
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
FileInputStream fis = new FileInputStream(path);// 创建文件的输入流
OutputStream os = response.getOutputStream();// 得到一个文件输出流,可以向浏览器输出数
int len = 0;// 表示实际每次读取多少个字节
最近在做一个网站后台,用到了文件的下载,整理出来,以供日后查阅,也供大家参考。
1:首先创建一个jsp,我取名为:fileDownload.jsp
主要代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
%>
byte[] buff = new byte[1024];// 创建一个缓冲字节数组
while ((len = fis.read(buff)) > 0) {
os.write(buff, 0, len);
}
fis.close();// 关闭资源
os.flush();
JSP文件下载功能的4种方法
JSP⽂件下载功能的4种⽅法对于⽹站来说,⽹站本⾝常常需要提供⼀些资源或者资料进⾏下载,说到下载莫过于最原始的⽅法就是在⽹页上提供下载的⽹址。
今天讲述的还有另外的⼏种实现⽂件下载的⽅法,对于哪种⽅法更好这也是看⾃⼰的需求。
1、最直接最简单的,⽅式是把⽂件地址直接放到html页⾯的⼀个链接中。
这样做的缺点是把⽂件在服务器上的路径暴露了,并且还⽆法对⽂件下载进⾏其它的控制(如权限)。
这个就不写⽰例了。
2、在服务器端把⽂件转换成输出流,写⼊到response,以response把⽂件带到浏览器,由浏览器来提⽰⽤户是否愿意保存⽂件到本地,⽰例如下:<%response.setContentType(fileminitype);response.setHeader("Location",filename);response.setHeader("Cache-Control", "max-age=" + cacheTime);//filename应该是编码后的(utf-8)response.setHeader("Content-Disposition", "attachment; filename=" + filename);response.setContentLength(filelength);OutputStream outputStream = response.getOutputStream();InputStream inputStream = new FileInputStream(filepath);byte[] buffer = new byte[1024];int i = -1;while ((i = inputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, i);}outputStream.flush();outputStream.close();inputStream.close();outputStream = null;%>3、既然是JSP的话,还有⼀种⽅式就是⽤Applet来实现⽂件的下载。
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.。
chap5_JSP中的文件操作
File类
File类的对象主要用来获取文件本身的一些 信息,例如文件所在的目录、文件的长度、 文件读写权限等,不涉及对文件的读写操作, 主要操作包括获取文件属性和管理目录 File对象的构造方法: File(String filename); File(String directoryPath, String filename ); File(File f, String filename);
11
FlieOutputStream类
构造函数: FileOutputStream(String name); FileOutputStream(File file); 参数name和file指定的文件称为输出流的目的地,通 过向输出流写入数据把信息送往目的地 一般是在try-catch语句的try块部分创建输出流对象, 在catch(捕获)部分检测并处理这个异常 void write(byte b[]); void write(byte b[], int off, int len);
17
RandomAccessFile类
RandomAccessFile流的指向既可以作为源,也可以 作为目的地 当需要对一个文件进行读写操作时,可以创建一个指 向该文件的RandomAccessFile流,这样既可以读也 可以写 RandomAccessFile(String name, String mode) RandomAccessFile(File file, String mode) 参数mode取r或rw,决定对流文件的访问权限 方法seek(long a)用来移动RandomAccessFile流指 向的文件的指针,参数a确定文件指针距离文件开头的 字节位置 方法getFilePointer()可以获取当前文件指针的位置
JavaWeb实现文件上传下载功能实例详解
JavaWeb实现⽂件上传下载功能实例详解在Web应⽤系统开发中,⽂件上传和下载功能是⾮常常⽤的功能,今天来讲⼀下JavaWeb中的⽂件上传和下载功能的实现。
⽂件上传概述1、⽂件上传的作⽤例如⽹络硬盘!就是⽤来上传下载⽂件的。
在智联招聘上填写⼀个完整的简历还需要上传照⽚呢。
2、⽂件上传对页⾯的要求上传⽂件的要求⽐较多,需要记⼀下:必须使⽤表单,⽽不能是超链接表单的method必须是POST,⽽不能是GET表单的enctype必须是multipart/form-data在表单中添加file表单字段,即<input type=”file” name=”xxx”/><form action="${pageContext.request.contextPath }/FileUploadServlet"method="post" enctype="multipart/form-data">⽤户名:<input type="text" name="username"/><br/>⽂件1:<input type="file" name="file1"/><br/>⽂件2:<input type="file" name="file2"/><br/><input type="submit" value="提交"/></form>3、⽐对⽂件上传表单和普通⽂本表单的区别通过httpWatch查看“⽂件上传表单”和“普通⽂本表单”的区别。
⽂件上传表单的enctype=”multipart/form-data”,表⽰多部件表单数据;普通⽂本表单可以不设置enctype属性:当method=”post”时,enctype的默认值为application/x-www-form-urlencoded,表⽰使⽤url编码正⽂当method=”get”时,enctype的默认值为null,没有正⽂,所以就不需要enctype了对普通⽂本表单的测试:<form action="${pageContext.request.contextPath }/FileUploadServlet" method="post">⽤户名:<input type="text" name="username"/><br/>⽂件1:<input type="file" name="file1"/><br/>⽂件2:<input type="file" name="file2"/><br/><input type="submit" value="提交"/></form>通过httpWatch测试,查看表单的请求数据正⽂,我们发现请求中只有⽂件名称,⽽没有⽂件内容。
jspSmartUpload使用文档
一、安装篇jspSmartUpload是由网站开发的一个可免费使用的全功能的文件上传下载组件,适于嵌入执行上传下载操作的JSP文件中。
该组件有以下几个特点:1、使用简单。
在JSP文件中仅仅书写三五行JAVA代码就可以搞定文件的上传或下载,方便。
2、能全程控制上传。
利用jspSmartUpload组件提供的对象及其操作方法,可以获得全部上传文件的信息(包括文件名,大小,类型,扩展名,文件数据等),方便存取。
3、能对上传的文件在大小、类型等方面做出限制。
如此可以滤掉不符合要求的文件。
4、下载灵活。
仅写两行代码,就能把Web服务器变成文件服务器。
不管文件在Web服务器的目录下或在其它任何目录下,都可以利用jspSmartUpload进行下载。
5、能将文件上传到数据库中,也能将数据库中的数据下载下来。
这种功能针对的是MYSQL 数据库,因为不具有通用性,所以本文不准备举例介绍这种用法。
jspSmartUpload组件可以从网站上自由下载,压缩包的名字是jspSmartUpload.zip。
下载后,用WinZip或WinRAR将其解压到Tomcat的webapps目录下(本文以Tomcat服务器为例进行介绍)。
解压后,将webapps/jspsmartupload目录下的子目录Web-inf名字改为全大写的WEB-INF,这样一改jspSmartUpload类才能使用。
因为Tomcat对文件名大小写敏感,它要求Web应用程序相关的类所在目录为WEB-INF,且必须是大写。
接着重新启动Tomcat,这样就可以在JSP文件中使用jspSmartUpload组件了。
注意,按上述方法安装后,只有webapps/jspsmartupload目录下的程序可以使用jspSmartUpload组件,如果想让Tomcat服务器的所有Web应用程序都能用它,必须做如下工作:1.进入命令行状态,将目录切换到Tomcat的webapps/jspsmartupload/WEB-INF目录下。
DiskFileItemFactory实现文件上传 FileInputStream下载
java用DiskFileItemFactory实现文件上传FileInputStream下载以下以图片上传下载做为例子,拷贝以下代码可以实现其下载上传功能==================================================================上传的jsp页面代码://下载图片的函数function downfile(){window.location.href = "downTemplate.jsp";}</script><title>文件上传和下载测试</title></head><body><form method="post" action="fileload" enctype="multipart/form-data"><input type="file" id="sign" name="sign" value=""><br><input type="submit" value="submit" ><br/><input type="button" onclick="downfile()" value="image down" ></form></body></html>================================================================== 上传文件的action类方法package com.unionpay.upop.gan.test;import java.io.File;import java.util.Iterator;import java.util.List;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import mons.fileupload.FileItem;import mons.fileupload.disk.DiskFileItemFactory;import mons.fileupload.servlet.ServletFileUpload;public class UploadFileServlet extends HttpServlet {private static final long serialVersionUID = -6247574514957274823L;static int i= 0;public void init() {}public void service(HttpServletRequest request, HttpServletResponse response){try {request.setCharacterEncoding("UTF-8") ;response.setCharacterEncoding("UTF-8") ;String loadpath=request.getSession().getServletContext().getRealPath("/image/"); //上传文件存放目录File f = new File(loadpath);if(!f.exists()){f.mkdir();}DiskFileItemFactory factory = new DiskFileItemFactory() ;factory.setSizeThreshold(4*1024) ;ServletFileUpload upload = new ServletFileUpload(factory) ;upload.setSizeMax(4*1024*1024);List<FileItem> list = upload.parseRequest(request) ;Iterator<FileItem> iter = list.iterator() ;while(iter.hasNext()){System.out.println("444");FileItem item = iter.next();String name = item.getName();name = name.substring(stIndexOf(");File file = new File(loadpath+"//"+name);item.write(file);}} catch (Exception e) {e.printStackTrace();}}}==================================================================在这里下载文件的代码我用JSP做为servlet< import="java.io.File"%>< import="java.io.FileInputStream"%>< import=".URLEncoder"%>< language="java" contentType="application/x-msdownload" pageEncoding="UTF-8"%> <TITLE>下载文件</TITLE><%StringBuffer classpath = newStringBuffer(request.getSession().getServletContext().getRealPath("/"));String templateFile = classpath+"/image/test.gif";response.reset();//可以加也可以不加response.setContentType("application/x-download");java.io.OutputStream outp = null;java.io.FileInputStream in = null;try {File file = new File(templateFile);response.addHeader( "Content-Disposition", "attachment;filename=" +URLEncoder.encode(file.getName(), "UTF-8") );outp = response.getOutputStream();in = new FileInputStream(file);byte[] b = new byte[1024];int i = 0;while ((i = in.read(b)) > 0) {outp.write(b, 0, i);}outp.flush();out.clear();out = pageContext.pushBody();} catch (Exception e) {e.printStackTrace();} finally {if (in != null) {try {in.close();}catch(Exception e){}in = null; }}%>。
SpringBoot+thymeleaf实现文件上传下载功能
SpringBoot+thymeleaf实现⽂件上传下载功能最近同事问我有没有有关于技术的电⼦书,我打开电脑上的⼩书库,但是邮件发给他太⼤了,公司⼜禁⽌⽤⽂件夹共享,于是花半天时间写了个⼩的⽂件上传程序,部署在⾃⼰的Linux机器上。
提供功能: 1 .⽂件上传 2.⽂件列表展⽰以及下载原有的上传那块很丑,写了点js代码优化了下,最后界⾯显⽰如下图:先给出成果,下⾯就⼀步步演⽰怎么实现。
1.新建项⽬⾸先当然是新建⼀个spring-boot⼯程,你可以选择在⽹站初始化⼀个项⽬或者使⽤IDE的Spring Initialier功能,都可以新建⼀个项⽬。
这⾥我从IDEA新建项⽬:下⼀步,然后输⼊group和artifact,继续点击next:这时候出现这个模块选择界⾯,点击web选项,勾上Web,证明这是⼀个webapp,再点击Template Engines选择前端的模板引擎,我们选择Thymleaf,spring-boot官⽅也推荐使⽤这个模板来替代jsp。
最后⼀步,然后等待项⽬初始化成功。
2.pom设置⾸先检查项⽬需要添加哪些依赖,直接贴出我的pom⽂件:<?xml version="1.0" encoding="UTF-8"?><project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance" xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.shuqing28</groupId><artifactId>upload</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>upload</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.9.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- https:///artifact/org.webjars/bootstrap --><dependency><groupId>org.webjars</groupId><artifactId>bootstrap</artifactId><version>3.3.5</version></dependency><!-- https:///artifact/org.webjars.bower/jquery --><dependency><groupId>org.webjars.bower</groupId><artifactId>jquery</artifactId><version>2.2.4</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>可以查看到 spring-boot-starter-thymeleaf 包含了webapp,最后两个webjars整合了bootstrap和jquery,其它的等代码⾥⽤到再说。
js实现文件上传功能后台使用MultipartFile
js实现文件上传功能后台使用MultipartFile在前端使用JavaScript实现文件上传功能,可以通过使用`FormData`对象来实现。
首先,我们需要创建一个HTML表单,并添加一个文件输入字段。
```html<form id="uploadForm"><input type="file" name="file" id="fileInput"><button type="submit">上传</button></form>```接下来,在JavaScript中,我们可以监听表单的提交事件,并在事件处理程序中获取文件数据,并将其发送到后台。
```javascriptdocument.getElementById('uploadForm').addEventListener('subm it', function(event)event.preventDefault(; // 阻止表单默认提交行为var fileInput = document.getElementById('fileInput');var file = fileInput.files[0];var formData = new FormData(;formData.append('file', file);//发送文件数据到后台var xhr = new XMLHttpRequest(;xhr.open('POST', '/upload'); // 替换成你的后台接口地址xhr.send(formData);});```在后台使用Spring框架时,可以使用`MultipartFile`来接收上传的文件。
JSP技术实现上传压缩文件及文件相关信息并解压
JSP技术实现上传压缩文件及文件相关信息并解压
韩银锋
【期刊名称】《电脑编程技巧与维护》
【年(卷),期】2015(0)7
【摘要】使用JSP技术实现上传压缩文件包括文件及其描述信息,并在上传后将压缩文件解压到指定的文件夹中.
【总页数】2页(P18-19)
【作者】韩银锋
【作者单位】西安航空职业技术学院,西安710089
【正文语种】中文
【相关文献】
1.一种基于日志结构的自动压缩/解压缩文件系统的实现方案 [J], 甄成;张跃;张衍胜;梁金千
2.在JSP中实现文件上传下载的相关问题及改进方案 [J], 戴洋;陈海
3.信息技术教学系统中利用asp实现文件上传 [J], 董瑞杰
4.信息化管理实现学生电子文件上传解决方案 [J], 庄李平
5.在Windows XP中轻松实现压缩解压缩文件 [J], 张鹏
因版权原因,仅展示原文概要,查看原文内容请购买。
Jsp页面实现文件上传下载
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对象。
JSP上传文件
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中实现文件上传下载的相关问题及改进方案
JP技术 , S 设计完成 B S / 模式的科 技综合信息管理系 统。在实际的设计过程中, 遇到了 文件上传及下载的
问题 , 于是查阅了许多相关 的资料 , 同时在 网络上参 与此类问题的讨论 , 从中发现基于 J S P平台的文件上 传下载存在诸多问题 , 缺乏系统的、 完善的解决办法。 本文提供笔者在应用 中遇到的问题及采取 的解决办 法, 并给出经过测试的部分关键源代码。
维普资讯
2 O 年第 1 O6 0期 文章编号 :0627 (06 1- 70 10-4 520 )0( .4  ̄
计 算 机 与 现 代 化 n l N Y IN AH A sy 且 U XA D I U A
总第 14期 3
在 JP中实现文件上传下载的相关 问题及 改进 方案 S
BS / 体系结构, 应用 网络协 同工作模 式 , 为科技项 目
的申报 、 评审 、 立项 、 进度跟踪 与资金管理 、 验收和评
奖等环节提供全方位的服务 , 实现合理化建议 和技改
项 目的在线 申报与鉴定 , 实现科技人员考核的业绩统 计和在线打分。并 由此实现科技信息内容管理与网 络发布, 在线生成科技管理业务报表 , 辅助领导决策 , 推进科技研发管理现代化。本系统的开发环境为: 服
先介绍一个 JP S 环境下用于文件一传下载的组件
S aU l d m r pod是 由 、v .pm r em 网站 m r p a。S aU l t o t a v、 i sa .o 、v s t
戴 洋, 陈 海
( 南昌大学信 息工程 学院, 江西 南 昌 30 9 3 2) 0 摘 要: 绍 J 环境下文件上传下载 的方法和工具 , 介 S P 对设计 实现 上传 文件 功能过程 中可能 遇到 的问题进行 分析 , 并结合
js前端实现文件流下载的几种方式
js前端实现⽂件流下载的⼏种⽅式后端是⽤Java写的⼀个下载的接⼝,返回的是⽂件流,需求:点击,请求,下载利⽤iframe实现⽂件流下载//把上⼀次创建的iframe删掉,不然随着下载次数的增多页⾯上会⼀堆的iframevar haveIframe = $("iframe")if(haveIframe){haveIframe.remove();}downloadFile(url);function downloadFile(url) {try{var elemIF = document.createElement("iframe");elemIF.src = url+'?pSize=1&pNum=1&flag=1&sts=Y';elemIF.style.display = "none";document.body.appendChild(elemIF);}catch(e){zzrw.alert("下载异常!");}}利⽤from表单实现⽂件流下载//同样道理,把上⼀次创建的form删掉,不然随着下载次数的增多页⾯上会⼀堆的formvar haveForm = $("#downloadfileform")if(haveForm){$("#downloadfileform").remove();}var $eleForm = $("<form id='downloadfileform' method='get'><input id='input_data' name='data' type='hidden'>" +"<input id='pSize' name='pSize' value='"+obj.pSize+"' type='hidden'>"+"<input id='pNum' name='pNum' value='"+obj.pNum+"' type='hidden'>"+"<input id='flag' name='flag' value='"+obj.flag+"' type='hidden'>"+"<input id='sts' name='sts' value='"+obj.sts+"' type='hidden'>"+"</form>");$eleForm.attr("action",url);$(document.body).append($eleForm);//提交表单,实现下载$eleForm.submit();。
jsp实现下载excel,word,pdf,jgp,gif,xml,js过滤器实现文档
下面代码有选择的粘贴进自己项目即可,其实现解决了tomcat、resin服务器中文下载乱码问题。
web.xml配置如下<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="/xml/ns/javaee"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/xml/ns/javaee/xml/ns/javaee/web-app_2_5.xsd"><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><filter><filter-name>downLoad</filter-name><filter-class>com.tangdi.DownLoadFilter</filter-class></filter><filter-mapping><filter-name>downLoad</filter-name><url-pattern>*.downLoad</url-pattern></filter-mapping></web-app>Jsp页面配置如下其下载利用a标签进行连接,前提是服务器上下载文件路径已知需要引进el表达式和jquery.<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%@ taglib uri="/jsp/jstl/core" prefix="c"%><script src="${pageContext.request.contextPath}/js/jquery-1.4.4.min.js" type="text/javascript"></script><html><head><script>$(function(){var$href='${pageContext.request.contextPath}'+"/20159.downLoad?filePath=";//+encodeURICompo nent("中国.downLoad");$("#testHref").children("td").each(function(){var $id=$(this).children(":first").attr("id");var $tmpHref="";if($id=="txt"){$tmpHref=$href+"E:/apache-tomcat-6.0.35/apache-tomcat-6.0.35/webapps/MyTry/test/"+"203123 4_这是txt.txt";}else if($id=="pdf"){$tmpHref=$href+"E:/apache-tomcat-6.0.35/apache-tomcat-6.0.35/webapps/MyTry/test/"+"这是pdf.pdf";}else if($id=="excel"){$tmpHref=$href+"这是excel.xls";}else if($id=="word"){$tmpHref=encodeURI($href+"这是doc.doc","ISO8859-1");}else if($id=="jpg"){$tmpHref=$href+"这是jpg.jpg";}else if($id=="js"){$tmpHref=$href+"这是js.js";}else if($id=="jsp"){$tmpHref=$href+"这是jsp.jsp";}else if($id=="html"){$tmpHref=$href+"这是html.html";}$(this).children(":first").attr("href",$tmpHref);});});</script></head><body><div><table><tr id="testHref"><td><a id="txt" href="#">txt</a></td><td><a id="pdf" href="#">pdf</a></td><td><a id="excel" href="#">excel</a></td><td><a id="word" href="#">word</a></td><td><a id="xml" href="#">xml</a></td><td><a id="jpg" href="#">jpg</a></td><td><a id="gif" href="#">gif</a></td><td><a id="js" href="#">js</a></td><td><a id="jsp" href="#">jsp</a></td><td><a id="html" href="#">html</a></td></tr></table></div></body></html>过滤器filter配置如下package com.tangdi;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.PrintWriter;import .URLDecoder;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class DownLoadFilter implements Filter {public void destroy() {}public void doFilter(ServletRequest request1, ServletResponse response1,FilterChain arg2) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) request1;HttpServletResponse response = (HttpServletResponse) response1;//request.setCharacterEncoding("UTF-8");//String filePath = new String(request.getParameter("filePath").getBytes("ISO8859-1"), "UTF-8");request.setCharacterEncoding("ISO8859-1");String filePath = new String(request.getParameter("filePath").getBytes("ISO8859-1"),"UTF-8");System.out.println("*****************************************************filePat h is :" + filePath);String suffix = filePath.substring(stIndexOf(".") + 1);System.out.println("********************suffix is:"+suffix);String contentType = getContentType(suffix);//获得尾缀设置不同contentTypeString contentDisposition = "attachment; filename="+new String(filePath.substring(stIndexOf("_")+1));System.out.println("********************************************"+contentDisposit ion);response.setCharacterEncoding("ISO8859-1");response.setContentType(contentType);response.setHeader("Content-disposition", new String(contentDisposition.getBytes("UTF-8"),"ISO8859-1"));try {InputStream is = new FileInputStream(filePath);OutputStream os = response.getOutputStream();int byteRead;byte[] buffer = new byte[1024];while ((byteRead = is.read(buffer)) != -1) {os.write(buffer, 0, byteRead);}os.flush();os.close();} catch (Exception e) {e.printStackTrace();}}/**** @param suffix 下载文件尾缀* @return 返回不同response.contentType*/public String getContentType(String suffix) {if (suffix.equals("txt")) {return "text/plain";} else if(suffix.equals("doc") || suffix.equals("docx")) {return "application/msword;charset=gb2312";} else if(suffix.equals("xls") || suffix.equals("xlsx")) {return "application/-excel";} else if(suffix.equals("pdf")) {return "application/pdf";}else if(suffix.equals("gif")){return "image/gif" ;}else if(suffix.equals("jpg")){return "image/jpeg" ;}else if(suffix.equals("htm")||suffix.equals("html")||suffix.equals("jsp")){return "text/html" ;}else if(suffix.equals("xml")){return "text/xml" ;}else if(suffix.equals("js")){return "application/x-javascript" ;}return "application/octet-stream";}public void init(FilterConfig config) throws ServletException {}}注:其中编码ISO8859-1不能乱改,否则出现解析路径错误或者下载文件出错。
java实现文件上传和下载
文件上传在web应用中非常普遍,要在jsp环境中实现文件上传功能是非常容易的,因为网上有许多用java开发的文件上传组件,本文以commons-fileupload组件为例,为jsp应用添加文件上传功能。
common-fileupload组件是apache的一个开源项目之一,可以从/commons/fileupload/(/commons/fileupload/)下载。
用该组件可实现一次上传一个或多个文件,并可限制文件大小。
代码下载后解压zip包,将commons-fileupload-1.0.jar复制到tomcat的webapps你的webappWEB-INFlib下,目录不存在请自建目录。
新建一个servlet: Upload.java用于文件上传:import java.io.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;import mons.fileupload.*;public class Upload extends HttpServlet {private String uploadPath = "C:upload"; // 上传文件的目录private String tempPath = "C:uploadtmp"; // 临时文件目录public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{}}在doPost()方法中,当servlet收到浏览器发出的Post请求后,实现文件上传。
以下是示例代码:public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{try {DiskFileUpload fu = new DiskFileUpload();// 设置最大文件尺寸,这里是4MBfu.setSizeMax(4194304);// 设置缓冲区大小,这里是4kbfu.setSizeThreshold(4096);// 设置临时目录:fu.setRepositoryPath(tempPath);// 得到所有的文件:List fileItems = fu.parseRequest(request);Iterator i = fileItems.iterator();// 依次处理每一个文件:while(i.hasNext()) {FileItem fi = (FileItem)i.next();// 获得文件名,这个文件名包括路径:String fileName = fi.getName();// 在这里可以记录用户和文件信息// 写入文件,暂定文件名为a.txt,可以从fileName中提取文件名:fi.write(new File(uploadPath + "a.txt"));}}catch(Exception e) {// 可以跳转出错页面}}如果要在配置文件中读取指定的上传文件夹,可以在init()方法中执行:public void init() throws ServletException {uploadPath = ....tempPath = ....// 文件夹不存在就自动创建:if(!new File(uploadPath).isDirectory())new File(uploadPath).mkdirs();if(!new File(tempPath).isDirectory())new File(tempPath).mkdirs();}编译该servlet,注意要指定classpath,确保包含commons-upload-1.0.jar和tomcatcommonlibservlet-api.jar。
jspstruts1struts2上传文件
一.在JSP环境中利用Commons-fileupload组件实现文件上传1.页面upload.jsp清单如下:Java代码1.<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>2.3.<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML4.01 Transitional//EN">4.<html>5. <head>6. <title>The FileUpload Demo</title>7. </head>8.9. <body>10. <form action="UploadFile" method="post" enctype="multipart/form-data">11. <p><input type="text" name="fileinfo" value="">文件介绍</p>12. <p><input type="file" name="myfile" value="阅读文件"></p>13. <p><input type="submit" value="上传"></p>14. </form>15. </body>16.</html>注意:在上传表单中,既有一般文本域也有文件上传域2.FileUplaodServlet.java清单如下:Java代码1.package org.chris.fileupload;2.3.import java.io.File;4.import java.io.IOException;5.import java.util.Iterator;6.import java.util.List;7.8.import javax.servlet.ServletException;9.import javax.servlet.http.*;10.11.import org.apachemons.fileupload.FileItem;12.import org.apachemons.fileupload.FileItemFactory;13.import org.apachemons.fileupload.disk.DiskFileItemFactory;14.import org.apachemons.fileupload.servlet.ServletFileUpload;15.16.public class FileUplaodServlet extends HttpServlet {17.18. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {19. doPost(request, response);20. }21.22. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {23.24. request.setCharacterEncoding("UTF-8");25.26. //文件的上传部份27. boolean isMultipart = ServletFileUpload.isMultipartContent(request);28.29. if(isMultipart)30. {31. try {32. FileItemFactory factory = new DiskFileItemFactory();33. ServletFileUpload fileload = new ServletFileUpload(factory);34.35.// 设置最大文件尺寸,那个地址是4MB36. fileload.setSizeMax(4194304);37. List<FileItem> files = fileload.parseRequest(request);38. Iterator<FileItem> iterator = files.iterator();39. while(iterator.hasNext())40. {41. FileItem item = iterator.next();42. if(item.isFormField())43. {44. String name = item.getFieldName();45. String value = item.getString();46. System.out.println("表单域名为: " + name + "值为: " + value);47. }else48. {49. //取得取得文件名,此文件名包括途径50. String filename = item.getName();51. if(filename != null)52. {53. File file = new File(filename);54. //若是此文件存在55. if(file.exists()){56. File filetoserver = new File("d:\\upload\\",file.getName());57. item.write(filetoserver);58. System.out.println("文件 " + filetoserver.getName() + " 上传成功!!");59. }60. }61. }62. }63. } catch (Exception e) {64. System.out.println(e.getStackTrace());65. }66. }67. }68.}3.web.xml清单如下:Java代码1.<?xml version="1.0" encoding="UTF-8"?>2.<web-app version="2.4"3. xmlns="java.sun/xml/ns/j2ee"4. xmlns:xsi="/2001/XMLSchema-instance"5. xsi:schemaLocation="java.sun/xml/ns/j2ee6. java.sun/xml/ns/j2ee/web-app_2_4.xsd">7.8. <servlet>9. <servlet-name>UploadFileServlet</servlet-name>10. <servlet-class>11. org.chris.fileupload.FileUplaodServlet12. </servlet-class>13. </servlet>14.15. <servlet-mapping>16. <servlet-name>UploadFileServlet</servlet-name>17. <url-pattern>/UploadFile</url-pattern>18. </servlet-mapping>19.20. <welcome-file-list>21. <welcome-file>/Index.jsp</welcome-file>22. </welcome-file-list>23.24.</web-app>二.在strut1.2中实现1.上传页面file.jsp 清单如下:Java代码1.<%@ page language="java" pageEncoding="ISO-8859-1"%>2.<%@ taglib uri="/struts/tags-bean" prefix="bean"%>3.<%@ taglib uri="/struts/tags-html" prefix="html"%>4.5.<html>6. <head>7. <title>JSP for FileForm form</title>8. </head>9. <body>10. <html:form action="/file" enctype="multipart/form-data">11. <html:file property="file1"></html:file>12. <html:submit/><html:cancel/>13. </html:form>14. </body>15.</html>2.FileAtion.java的清单如下:Java代码1./*2. * Generated by MyEclipse Struts3. * Template path: templates/java/JavaClass.vtl4. */5.package action;6.7.import java.io.*;8.9.import javax.servlet.http.HttpServletRequest;10.import javax.servlet.http.HttpServletResponse;11.import org.apache.struts.action.Action;12.import org.apache.struts.action.ActionForm;13.import org.apache.struts.action.ActionForward;14.import org.apache.struts.action.ActionMapping;15.import org.apache.struts.upload.FormFile;16.17.import form.FileForm;18.19./**20. * @author Chris21. * Creation date: 6-27-202022. *23. * XDoclet definition:24. * @struts.action path="/file" name="fileForm" input="/file.jsp"25. */26.public class FileAction extends Action {27. /*28. * Generated Methods29. */30.31. /**32. * Method execute33. * @param mapping34. * @param form35. * @param request36. * @param response37. * @return ActionForward38. */39. public ActionForward execute(ActionMapping mapping, ActionForm form,40. HttpServletRequest request, HttpServletResponse response) {41. FileForm fileForm = (FileForm) form;42. FormFile file1=fileForm.getFile1();43. if(file1!=null){44. //上传途径45. String dir=request.getSession(true).getServletContext().getRealPath("/upload");46. OutputStream fos=null;47. try {48. fos=new FileOutputStream(dir+"/"+file1.getFileName());49. fos.write(file1.getFileData(),0,file1.getFileSize());50. fos.flush();51. } catch (Exception e) {52. // TODO Auto-generated catch block53. e.printStackTrace();54. }finally{55. try{56. fos.close();57. }catch(Exception e){}58. }59. }60. //页面跳转61. return mapping.findForward("success");62. }63.}3.FileForm.java的清单如下:Java代码1.package form;2.3.import javax.servlet.http.HttpServletRequest;4.import org.apache.struts.action.ActionErrors;5.import org.apache.struts.action.ActionForm;6.import org.apache.struts.action.ActionMapping;7.import org.apache.struts.upload.FormFile;8.9./**10. * @author Chris11. * Creation date: 6-27-202012. *13. * XDoclet definition:14. * @struts.form name="fileForm"15. */16.public class FileForm extends ActionForm {17. /*18. * Generated Methods19. */20. private FormFile file1;21. /**22. * Method validate23. * @param mapping24. * @param request25. * @return ActionErrors26. */27. public ActionErrors validate(ActionMapping mapping,28. HttpServletRequest request) {29. // TODO Auto-generated method stub30. return null;31. }32.33. /**34. * Method reset35. * @param mapping36. * @param request37. */38. public void reset(ActionMapping mapping, HttpServletRequest request) {39. // TODO Auto-generated method stub40. }41.42. public FormFile getFile1() {43. return file1;44. }45.46. public void setFile1(FormFile file1) {47. this.file1 = file1;48. }49.}4.struts-config.xml的清单如下:Java代码1.<?xml version="1.0" encoding="UTF-8"?>2.<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "/d tds/struts-config_1_2.dtd">3.4.<struts-config>5. <data-sources />6. <form-beans >7. <form-bean name="fileForm" type="form.FileForm" />8.9. </form-beans>10.11. <global-exceptions />12. <global-forwards />13. <action-mappings >14. <action15. attribute="fileForm"16. input="/file.jsp"17. name="fileForm"18. path="/file"19. type="action.FileAction"20. validate="false">21. <forward name="success" path="/file.jsp"></forward>22. </action>23.24. </action-mappings>25.26. <message-resources parameter="ApplicationResources" />27.</struts-config>5.web.xml代码清单如下:Java代码1.<?xml version="1.0" encoding="UTF-8"?>2.<web-app xmlns="java.sun/xml/ns/j2ee" xmlns:xsi="w/2001/XMLSchema-instance" version="2.4" xsi:schemaLocatio n="java.sun/xml/ns/j2ee java.sun/xml/ns/j2ee/web-app_2_4.xsd">3. <servlet>4. <servlet-name>action</servlet-name>5. <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>6. <init-param>7. <param-name>config</param-name>8. <param-value>/WEB-INF/struts-config.xml</param-value>9. </init-param>10. <init-param>11. <param-name>debug</param-name>12. <param-value>3</param-value>13. </init-param>14. <init-param>15. <param-name>detail</param-name>16. <param-value>3</param-value>17. </init-param>18. <load-on-startup>0</load-on-startup>19. </servlet>20. <servlet-mapping>21. <servlet-name>action</servlet-name>22. <url-pattern>*.do</url-pattern>23. </servlet-mapping>24.</web-app>三.在struts2中实现(以图片上传为例)1.FileUpload.jsp代码清单如下:Java代码1.<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>2.<%@ taglib prefix="s" uri="/struts-tags" %>3.<html>4. <head>5. <title>The FileUplaodDemo In Struts2</title>6. </head>7.8. <body>9. <s:form action="fileUpload.action" method="POST" enctype="multipart/form-data">10. <s:file name="myFile" label="MyFile" ></s:file>11. <s:textfield name="caption" label="Caption"></s:textfield>12. <s:submit label="提交"></s:submit>13. </s:form>14. </body>15.</html>2.ShowUpload.jsp的功能清单如下:Java代码1.<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>2.<%@ taglib prefix="s" uri="/struts-tags" %>3.<html>4. <head>5. <title>ShowUpload</title>6. </head>7.8. <body>9. <div style ="padding: 3px; border: solid 1px #cccccc; text-align: center" >10. <img src ='UploadImages/<s:property value ="imageFileName"/> '/>11. <br />12. <s:property value ="caption"/>13. </div >14. </body>15.</html>3.FileUploadAction.java的代码清单如下:Java代码1.package com.chris;2.3.import java.io.*;4.import java.util.Date;5.6.import org.apache.struts2.ServletActionContext;7.8.9.import com.opensymphony.xwork2.ActionSupport;10.11.public class FileUploadAction extends ActionSupport{12.13. private static final long serialVersionUID = 572146812454l;14. private static final int BUFFER_SIZE = 16 * 1024 ;15.16. //注意,文件上传时<s:file/>同时与myFile,myFileContentType,myFileFileName绑定17. //因此同时要提供myFileContentType,myFileFileName的set方式18.19. private File myFile; //上传文件20. private String contentType;//上传文件类型21. private String fileName; //上传文件名22. private String imageFileName;23. private String caption;//文件说明,与页面属性绑定24.25. public void setMyFileContentType(String contentType) {26. System.out.println("contentType : " + contentType);27. this .contentType = contentType;28. }29.30. public void setMyFileFileName(String fileName) {31. System.out.println("FileName : " + fileName);32. this .fileName = fileName;33. }34.35. public void setMyFile(File myFile) {36. this .myFile = myFile;37. }38.39. public String getImageFileName() {40. return imageFileName;41. }42.43. public String getCaption() {44. return caption;45. }46.47. public void setCaption(String caption) {48. this .caption = caption;49. }50.51. private static void copy(File src, File dst) {52. try {53. InputStream in = null ;54. OutputStream out = null ;55. try {56. in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);57. out = new BufferedOutputStream( new FileOutputStream(dst), BUFFER_SIZE);58. byte [] buffer = new byte [BUFFER_SIZE];59. while (in.read(buffer) > 0 ) {60. out.write(buffer);61. }62. } finally {63. if ( null != in) {64. in.close();65. }66. if ( null != out) {67. out.close();68. }69. }70. } catch (Exception e) {71. e.printStackTrace();72. }73. }74.75. private static String getExtention(String fileName) {76. int pos = stIndexOf(".");77. return fileName.substring(pos);78. }79.80.@Override81. public String execute() {82. imageFileName = new Date().getTime() + getExtention(fileName);83. File imageFile = new File(ServletActionContext.getServletContext().getRealPath("/UploadImages" ) + "/" + imageFileN ame);84. copy(myFile, imageFile);85. return SUCCESS;86. }87.}注:现在仅为方便实现Action因此继承ActionSupport,并Overrider execute()方式在struts2中任何一个POJO都能够作为Action4.struts.xml清单如下:Java代码1.<?xml version="1.0" encoding="UTF-8" ?>2.<!DOCTYPE struts PUBLIC3. "-//Apache Software Foundation//DTD Struts Configuration2.0//EN"4. "/dtds/struts-2.0.dtd">5.<struts>6. <package name="example" namespace="/" extends="struts-default">7. <action name="fileUpload" class="com.chris.FileUploadAction">8. <interceptor-ref name="fileUploadStack"/>9. <result>/ShowUpload.jsp</result>10. </action>11. </package>12.</struts>5.web.xml清单如下:Java代码1.<?xml version="1.0" encoding="UTF-8"?>2.<web-app version="2.4"3. xmlns="java.sun/xml/ns/j2ee"4. xmlns:xsi="/2001/XMLSchema-instance"5. xsi:schemaLocation="java.sun/xml/ns/j2ee6. java.sun/xml/ns/j2ee/web-app_2_4.xsd">7. <filter >8. <filter-name > struts-cleanup </filter-name >9. <filter-class >10. org.apache.struts2.dispatcher.ActionContextCleanUp11. </filter-class >12. </filter >13. <filter-mapping >14. <filter-name > struts-cleanup </filter-name >15. <url-pattern > /* </url-pattern >16. </filter-mapping >17.18. <filter>19. <filter-name>struts2</filter-name>20. <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>21. </filter>22. <filter-mapping>23. <filter-name>struts2</filter-name>24. <url-pattern>/*</url-pattern>25. </filter-mapping>26. <welcome-file-list>27. <welcome-file>Index.jsp</welcome-file>28. </welcome-file-list>29.30.</web-app>。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
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()此方法从该文件的当前文件指针开始读取第一个字节。
stIndexOf(char c)返回最后一次出现的指定字符在此字符串中的索引3、do_upload.jsp<%@ page contentType="text/html;charset=gb2312" language="java"%><%@ page import="java.io.*"%><html><head><meta http-equiv="content-Type" contentType="text/html;charset=gb2312"><title>上传</title></head><body><%try{String temp=(String)session.getId();//获得sessionIdFile f1=new File((String)request.getRealPath("photo")+"/",temp); //获得photo所在的目录,并加上sessionIdout.println(f1);FileOutputStream o=new FileOutputStream(f1); //文件输出流指向上传文件所在路径out.println(o);InputStream in=request.getInputStream(); //从客户端获得文件输入流int n;byte b[]=new byte[10000000];//设置缓冲数组的大小while((n=in.read(b))!=-1){o.write(b,0,n); //将数据从输入流读入到缓冲数组然后再从缓冲数组写入到文件中}o.close();in.close();//关闭输入流和文件输出流RandomAccessFile random=new RandomAccessFile(f1,"r"); //文件随机读取写入流int second=1;String secondLine=null;while(second<=2){secondLine=random.readLine();//读入临时文件名second++;}int position=stIndexOf('\\');String filename=new String((secondLine.substring(position+1,secondLine.length()-1)).getBytes("iso-8859-1"),"gb2312");//去掉临时文件名中的sessionId,获得文件名,并用iso-8859-1编码,避免出现中文乱码问题random.seek(0);long forthEnPosition=0;int forth=1;while((n=random.readByte())!=1&&forth<=4){if(n=='\n'){forthEnPosition=random.getFilePointer();forth++;}//去掉临时文件开头的4个'\n'字符}File f2=new File((String)request.getRealPath("photo")+"/",filename);//以文件的名创建另一个文件随机读取RandomAccessFile random2=new RandomAccessFile(f2,"rw");random.seek(random.length());long endPosition=random.getFilePointer(); //以文件的名创建另一个文件随机读取写入流int j=1;long mark=endPosition;while(mark<=0&&j<=6){ //去掉临时文件末尾的6个'\n'字符mark--;random.seek(mark);n=random.readByte();if(n=='\n'){endPosition=random.getFilePointer();j++;}}random.seek(forthEnPosition);long startPosition=random.getFilePointer();while(startPosition<endPosition-1){//将临时文件去掉头尾后写入到新建的文件中n=random.readByte();random2.write(n);startPosition=random.getFilePointer();}random2.close();random.close();f1.delete();%><script language="javascript">alert("文件上传成功!");history.back();</script><%}catch(Exception e){e.printStackTrace();out.println("上传文件失败!");}%>2 用smartUpload组件实现文件上传file_upload_smart_form.jsp<%@ page contentType="text/html;charset=gb2312" language="java"%><title>文件上传</title><body><h1 align="center">用smartUpload组件实现文件上传</h1><p align="center">请选择要上传的文件:</p><form method="post" action="ch4/file_upload_smart_do.jsp" ENCTYPE="multipart/form-data"><table width="75%" border="1" align="center"><tr><td height="25">上传文件1:</td><td height="25"><input type="FILE" name="FILE1" size="30"></td></tr><tr><td height="25">上传文件2:</td><td height="25"><input type="FILE" name="FILE2" size="30"></td></tr><tr><td height="25">上传文件3:</td><td height="25"><input type="FILE" name="FILE3" size="30"></td></tr><tr><td height="25">上传文件4:</td><td height="25"><input type="FILE" name="FILE4" size="30"></td></tr><tr><td colspan="2" align="center" height="40"><input type="submit" name="Submit" value="上传"><td></tr></table></form><body></html>file_upload_smart_do.jsp<%@ page contentType="text/html;charset=gb2312" language="java" import="java.util.*,com.jspsmart.upload.*"%><title>文件上传</title><body><div align="center"><%//新建一个SmartUpload对象SmartUpload su=new SmartUpload();//上传初始化su.initialize(pageContext);//设定上传限制//限制每个上传文件的最大长度su.setMaxFileSize(1000000);//限制总上传数据的长度su.setTotalMaxFileSize(4000000);//设定允许上传的文件(通过扩展名限制),公允许doc,txt,jpg,bmp,swf,rm,mp3,gif,mid文件su.setAllowedFilesList("doc,txt,jpg,bmp,swf,rm,mp3,gif,mid");//设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat,jsp,htm,html//扩展名的文件和没有扩展名的文件su.setDeniedFilesList("exe,bat,jsp,htm,html,,");//上传文件su.upload();//将上传文件全部保存到指定目录int count=su.save("/uploadfiles");out.println("<font color=red>"+count+"</font>个文件上传成功!<br>");//逐一提取上传文件信息,同时可保存文件for(int i=0;i<su.getFiles().getCount();i++){com.jspsmart.upload.File file=su.getFiles().getFile(i);//若文件表单中的文件选项没有选择文件则继续if(file.isMissing()){continue;}//显示当前文件信息out.println("<table border=1>");out.println("<tr><td>表单项名(FiledName)</td><td>"+file.getFieldName()+"</td></tr>");out.println("<tr><td>文件长度(Size)</td><td>"+file.getSize()+"</td></tr>");out.println("<tr><td>文件名(FileName)</td><td>"+file.getFileName()+"</td></tr>");out.println("<tr><td>文件扩展名(FileExt)</td><td>"+file.getFileExt()+"</td></tr>");out.println("<tr><td>文件全名(FilePathName)</td><td>"+file.getFilePathName()+"</td></tr>");out.println("</table><br>");}%></div></body>下载file_download_smart_form.jsp<%@ page contType="text/html;charset=gb2312" language="java"%><title>文件下载</title><body><h1 align="center">用SmartUpload组件实现文件下载</h1><div align="center"><a href="file_download_smart_do.jsp">单击下载</a></div></body>file_download_smart_do.jsp<%@ page contType="text/html,charset=gb2312" import="com.jspsmart.upload.*"%><%//新建一个SmartUpload对象SmartUpload su=new SmartUpload();//初始化su.initialize(pageContext);//设定contentDisposition为null以禁止济览器自动打开文件,保证单击链接后是下载文件.//若不设定,则下载文件的扩展名是.doc时,浏览器将自动用word打开它.su.setContentDisposition(null);//下载文件su.downloadFile("D:/ProgramFiles/web/tianxing2556/WebRoot/ch4/uploadfiles/864208.jpg");%>较复杂的上传下载smart_form.jsp<title>处理表单</title><body><h1 align="center">用jspSmartUpload组件处理表单</h1><hr width="90%"><div align="center"><form method="post" action="ch4/smart_form_do.jsp" name="form1" ENCTYPE="multipart/form-data"><table border="1" width="80%"><tr><td height="25">姓名:</td><td height="25" align="left"><input type="text" size="19" name="UserName"></td></tr><tr><td height="25">照片:</td><td height="25" align="left"><input type="file" name="Pic"></td></tr><tr><td height="25">性别:</td><td height="25" align="left"><input type="radio" name="Sex" value="男">男 <input type="radio" name="Sex" value="女">女</td></tr><tr><td height="25">所在地:</td><td height="25" align="left"><input type="text" name="Province"></td></tr><tr><td height="40" colspan="2" align="center"><input type="Submit" value="提交"></td></tr></table></form></div></body>smart_form_do.jsp<%@ page import="com.jspsmart.upload.*"%><title>用jspSmartUpload组件处理表单</title><body><h1 align="center">用jspSmartUpload组件处理表单</h1><hr width="90%"><%//新建一个SmartUpload对象SmartUpload su= new SmartUpload();//上传初始化su.initialize(pageContext);//设定允许上传的文件(通过扩展名限制),仅允许jpg,bmp,gif文件.su.setAllowedFilesList("jpg,bmp,gif");//上传文件su.upload();//将上传文件全部保存到指定目录su.save("D:/Program Files/web/tianxing2556/WebRoot/ch4/uploadfiles");%><div align="center"><table CELLSPACING="0" CELLPADDING="3" BORDER="1" WIDTH="80%"><tr><td>姓名:</td><td><%=su.getRequest().getParameter("UserName")%></td></tr><tr><td>照片:</td><td><img src="<%="D:/Program Files/web/tianxing2556/WebRoot/ch4/uploadfiles/"+su.getFiles().getFile(0).getFileName()%>"></ td></tr><tr><td>性别:</td><td><%=su.getRequest().getParameter("Sex") %></td></tr><tr><td>所在地:</td><td><%=su.getRequest().getParameter("Province") %></td></tr></table></div></body>。