jsp文件上传下载
- 格式:wps
- 大小:133.50 KB
- 文档页数:26
在jsp中使用smartupload组件上传文件jsp对上传文件的支持不象php中支持的那么好,直接做成了函数,也不象asp中要通过组件才能实现。
jsp中可以通过javabean来实现。
但是我们没有必要自己去写一个上载的bean,在网上已经有了很多成型的技术,smartupload就是其中的一个。
但是smartupload是将文件先读到服务器的内存中,所以上传太大的文件(超过100兆)有可能会出问题,也算是一个美中不足吧:)先说一下提交的页面,smartupload组件要求用字节流的方式来提交<FORM action="upload.jsp" encType=multipart/form-data method=post>。
下面就是个例子upload.htm:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0Transitional//EN"><!-- saved fromurl=(0057)http://localhost:8080/jspsmartfile/jsp/uploadTemplate.jsp --><HTML><HEAD><META content="text/html; charset=gb2312"http-equiv=Content-Type><META content="MSHTML 5.00.2920.0"name=GENERATOR></HEAD><BODY bgColor=#e6e6e6><BR><FORM action="upload.jsp" encType=multipart/form-data method=post><TABLE><TBODY><TR><TD><FONT color=#000000 face=helv,helveticasize=1> File: </FONT> <INPUT size=60 type=file name="file"></TD></TR><TR><TR><TD><FONT color=#000000 face=helv,helveticasize=1> File: </FONT> <INPUT size=60 type=file name="file1"></TD></TR><TR><TD><FONT color=#000000 face=helv,helveticasize=1> File: </FONT> <INPUT size=60 type=text name="text"></TD></TR><TR><TDalign=right><INPUT type=submit value=Sendname="send"></TD></TR></TBODY></TABLE></FORM></BODY ></HTML>再来看一下接收的页面,我们把文件上传到服务器以后就直接把它再存入数据库中:upload.jsp<%@ page contentType="text/html;charset=gb2312"%><%@ page import="java.sql.*"%><%@ page import="com.jspsmart.upload.*" %><%@ page import="DBstep.iDBManager2000.*"%><%//实例化上载beancom.jspsmart.upload.SmartUpload mySmartUpload=new com.jspsmart.upload.SmartUpload();//初始化mySmartUpload.initialize(pageContext);//设置上载的最大值mySmartUpload.setMaxFileSize(500 * 1024*1024);//上载文件mySmartUpload.upload();//循环取得所有上载的文件for (int i=0;i<mySmartUpload.getFiles().getCount();i++){//取得上载的文件com.jspsmart.upload.File myFile =mySmartUpload.getFiles().getFile(i);if (!myFile.isMissing()){//取得上载的文件的文件名String myFileName=myFile.getFileName();//取得不带后缀的文件名String suffix=myFileName.substring(0,stIndexOf('. '));//取得后缀名String ext= mySmartUpload.getFiles().getFile(0).getFileExt();//取得文件的大小int fileSize=myFile.getSize();//保存路径String aa=getServletContext().getRealPath("/")+"jsp\\";String trace=aa+myFileName;//取得别的参数Stringexplain=(String)mySmartUpload.getRequest().getParameter("text");Stringsend=(String)mySmartUpload.getRequest().getParameter("send");//将文件保存在服务器端myFile.saveAs(trace,mySmartUpload.SAVE_PHYSICAL);//下面的是将上载的文件保存到数据库中//将文件读到流中java.io.File file = new java.io.File(trace);java.io.FileInputStream fis = new java.io.FileInputStream(file); out.println(file.length());//打开数据库ResultSet result=null;String mSql=null;PreparedStatement prestmt=null;DBstep.iDBManager2000 DbaObj=new DBstep.iDBManager2000(); DbaObj.OpenConnection();//将文件写到数据库中mSql="insert into marklist(markname,password,marksize,markdate,MarkBody) values (?,?,?,?,?)";prestmt =DbaObj.Conn.prepareStatement(mSql);prestmt.setString(1, "aaa1");prestmt.setString(2, "0000");prestmt.setInt(3, fileSize);prestmt.setString(4, DbaObj.GetDateTime());prestmt.setBinaryStream(5,fis,(int)file.length());DbaObj.Conn.setAutoCommit(true) ;prestmt.executeUpdate();mit();out.println(("上载成功!!!").toString());}else{ out.println(("上载失败!!!").toString()); }}//与前面的if对应%>再说一下下载,下载分两种情况1。
1.最直接最简单的,方式是把文件地址直接放到html页面的一个链接中。
这样做的缺点是把文件在服务器上的路径暴露了,并且还无法对文件下载进行其它的控制(如权限)。
这个就不写示例了。
2.在服务器端把文件转换成输出流,写入到response,以response把文件带到浏览器,由浏览器来提示用户是否愿意保存文件到本地。
(示例如下)
3.既然是JSP的话,还有一种方式就是用Applet来实现文件的下载。
不过客户首先得信任你的这个Applet小程序,由这个程序来接受由servlet发送来的数据流,并写入到本地。
servlet端示例
JApplet端示例
4.顺便把JApplet上传文件的代码也贴上来. JApplet端示例
servlet端代码示例
总结:在文件的传输中是流的形式存在的,在硬盘上是文件的形式存在的。
我们要做的只是通过HttpServletRequest和HttpServletResponse,或者是response和request来发送流和读取流。
以及把文件转换成流或把流转换成文件的操作。
JAVA中的FtpClient与FTPClient,并实现jsp页面下载ftp服务器上的文件这段时间一直在研究Java如何访问Ftp,搞了一段时间了,也有一定的了解。
故此记录一下。
ftp和FTP我个人觉得FTP更符合我们程序员的口味,不管是方法命名还是API的详细与否,或者是开发平台的问题,FTP毕竟是Apache的东西,做的就是不错。
其实web开发中一般都会涉及到编码问题,所以web上传下载一定会有中文乱码的问题存在,而FTP对中文的支持比ftp要好多了。
使用ftpClient不需要导入其它jar包,只要你使用java语言开发就行了,而使用FTPClient 需要使用commons-net-1.4.1.jar和jakarta-oro-2.0.8.jar,当然jar版本随便你自己。
话不多说,上代码!FTP服务器的文件目录结构图:一、FtpClientFtpClient是属于JDK的包下面的类,但是jdkapi并没有对此作介绍,在中文支持上面也有一定的限制。
本段代码中的Ftp服务器的IP地址,用户名和密码均通过SystemConfig.properties文档获取Ftp_client.java[java]view plain copy1.package com.iodn.util;2.3.import java.io.ByteArrayOutputStream;4.import java.io.File;5.import java.io.FileInputStream;6.import java.io.FileOutputStream;7.import java.io.IOException;8.import java.util.ResourceBundle;9.import .TelnetInputStream;10.import .TelnetOutputStream;11.import .ftp.FtpClient;12.13.public class Ftp_client {14.15.//FTP客户端16.private FtpClient ftpClient;17.private ResourceBundle res=null;18./**19. * 连接FTP服务器20. * @param path 指定远程服务器上的路径21. */22.public Ftp_client(String path){23.24. res = ResourceBundle.getBundle("com.iodn.util.SystemConfig");//获取配置文件propeties文档中的数据25.try{26. ftpClient=new FtpClient(res.getString("Properties.ftpHostIp"));//如果不想使用配置文件即可将数据写死(如:192.168.1.10)27. ftpClient.login(res.getString("Properties.ftpUser"), res.getString("Properties.ftpPassword"));//Ftp服务器用户名和密码28. ftpClient.binary();29. System.out.println("Login Success!");30.if(path.length()!=0){31.//把远程系统上的目录切换到参数path所指定的目录(可不用设置,上传下载删除时加Ftp中的全路径即可)32. ftpClient.cd(path);33. }34. }catch(Exception e){35. e.printStackTrace();36. }37. }38.39./**40. * 上传文件41. * @param remoteFile42. * @param localFile43. */44.public boolean upload(String remoteFile, String localFile){45.boolean bool=false;46. TelnetOutputStream os=null;47. FileInputStream is=null;48.try{49. os=ftpClient.put(remoteFile);50. is=new FileInputStream(new File(localFile));51.byte[] b=new byte[1024];52.int c;53.while((c=is.read(b))!=-1){54. os.write(b, 0, c);55. }56. bool=true;57. }catch(Exception e){58. e.printStackTrace();59. System.out.println("上传文件失败!请检查系统FTP设置,并确认FTP服务启动");60. }finally{61.if(is!=null){62.try {63. is.close();64. } catch (IOException e) {65. e.printStackTrace();66. }67. }68.if(os!=null){69.try {70. os.close();71. } catch (IOException e) {72. e.printStackTrace();74. }75. closeConnect();76. }77.return bool;78. }79./**80. * 下载文件81. * @param remoteFile 远程文件路径(服务器端)82. * @param localFile 本地文件路径(客户端)83. */84.85.public void download(String remoteFile, String localFile) {86. TelnetInputStream is=null;87. FileOutputStream os=null;88.try{89.//获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。
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.。
18.Javaweb中⽂件的上传和下载【重要】Javaweb中⽂件的上传和下载⽂件上传⽂件上传指的是⽤户通过浏览器向服务器上传某个⽂件,服务器接收到该⽂件后会将该⽂件存储在服务器的硬盘中,通常不会存储在数据库中,这样可以减轻数据库的压⼒并且在⽂件的操作上更加灵活,常见的功能是上传头像图⽚。
⽂件上传的原理所谓的⽂件上传就是服务器端通过request对象获取输⼊流,将浏览器端上传的数据读取出来,保存到服务器端。
⽂件上传的要求提供form表单,表单的提交⽅式必须是post【get请求装不下那么多】form表单中的enctype属性必须是 multipart/form-data 【照着做就⾏】表单中提供input type=”file”上传输⼊域 【⽂件那个表单】先来个表单:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><figure><img src=""></figure><form action="#" method="post" accept-charset="utf-8" enctype="multipart/form-data"> <!--# 提交地址记得改!--><input type="file" name="photo"><br><input type="submit" value="上传头像"></form></body></html>来个Servlet来接收⼀下这个图⽚:package upload;import java.io.IOException;import java.io.InputStream;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/*** ⽂件上传例⼦*/public class file extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//获取请求的输⼊流InputStream is = request.getInputStream();//读取输⼊流中的数据int leng = 0;byte[] bytes = new byte[1024];while ((leng = is.read(bytes)) != -1) {//先打印控制台看看System.out.println(new String(bytes,0,leng));}}}打印出来的数据:------WebKitFormBoundarypM4ZEsxzVdl0NfZVContent-Disposition: form-data; name="photo"; filename="4-2 鍥剧墖鍒囨崲鏁堟灉[20210508-164643].jpg"Content-Type: image/jpeg反正⼀堆乱码但是头部我们是看的懂的就是⼀些标签的属性和上传的照⽚名字!和⽂件类型!如何解决?请看:FileUpload⼯具的使⽤在实际开发中通常会借助第三⽅⼯具来实现上传功能,应⽤较多的是apache旗下的Commons-fileupload。
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是由网站开发的一个可免费使用的全功能的文件上传下载组件,适于嵌入执行上传下载操作的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目录下。