- 浏览: 73593 次
- 性别:
- 来自: 北京
文章分类
最新评论
-
george.gu:
lqjacklee 写道怎么解决。。 First: Conf ...
Bad version number in .class file -
lqjacklee:
怎么解决。。
Bad version number in .class file -
flyqantas:
would you pleade left more mate ...
UML Extension
最近在项目中遇到一个下载文件的老问题。之所以说是老问题,因为在以前的很多项目中都遇到过,但是当时赶进度,所以在找到解决方案后就草草了事,没有深入的研究、总结一下各种方法,实乃憾事。
既然再次遇到,就不能放过。争取在依然很紧张的项目进度中,找出一点时间总结一下Java Web Application开发中涉及到的文件上传、下载解决方案。鉴于博客是写给自己看的,加上时间紧张,所以我会持续更新,不求一气呵成。
Upload File through Html FORM:
/html/body/form/@enctype: ENCTYPE determines how the form data is encoded. Whenever data is transmitted from one place to another, there needs to be an agreed upon means of representing that data.
FORM ENCTYPE has three different values:
- application/x-www-form-urlencoded : All characters are encoded in URL encoding before sent (this is default). Only value attribute inside form will be processed.
- multipart/form-data : data will be transformed in byte code stream. This value is required when you are using forms that have a file upload control. In
- text/plain : Spaces are converted to "+" symbols, but no special characters are encoded
So if you want to upload file through web, you have to first set form ENCTYPE to be "multipart/form-data".
Using pure Servlet:
In fact, file download and upload in Java Web Application are to manage files through InputStream from HttpServletRequest and OutputStream from HttpServletResponse.
Even we can simply the development and configuration by using some framework, but anyway we should know what is the kernel for file uploading and download.
File Upload web interface:
fileUpload.html <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Upload a File</title> </head> <body> <h1>Upload File </h1> <h2>Warning: Please make sure your web browser support file uploading.</h2> <form action="servlet/uploadServlet" method="POST" enctype="multipart/form-data "> Select a file to upload: <input type="file" size="40" name="upl-file"/> </BR> <input type="submit" value="Upload"/> <input type="reset" value="Reset"/> </form> </body> </html> |
Read file from HttpServletRequest Inputstream:
/** * Servlet.doPost: reads the uploaded data from the request and writes it to * a file. */ public void doPost(HttpServletRequest request, HttpServletResponse response) { DataInputStream in = null; try { // get content type of client request String contentType = request.getContentType();
// make sure content type is multipart/form-data if (contentType != null && contentType.indexOf("multipart/form-data ") != -1) { // open input stream from client to capture upload file in = new DataInputStream(request.getInputStream()) ; // get length of content data int formDataLength = request.getContentLength(); byte dataBytes[] = new byte[1024]; int bytesRead; while ((bytesRead = in.read(dataBytes)) != -1) { // write the data to server file. }
// here you can perform some other checks. } } catch (Exception e) { } } |
This is just a draft demo on how to upload file through servlet. There is no control on large files and user rights.
Download file through HttpServletResponse OutputStream
/** * Servlet.doPost: get data to be sent to client and output it through Response.outputStream. Web browser will pop-up a save file window to let User download file. */ public void doPost(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/csv"); response.setHeader("Content-Disposition", "attachment; filename=unknownModels.csv"); OutputStream out; // PrintWriter printWriter; try { out = response.getOutputStream(); // printWriter = response.getWriter(); ... // output your content with printWriter. It will output content to client. ... out.flush(); // printWriter.flush(); } catch (IOException e) { System.err.println("Met a error when download file."); System.exit(1); } } |
Content-Disposition used to define download file or open a file in web browsers:
attachment; filename=myfile.txt: download a file with default name myfile.txt inline; filename=myfile.txt: open the file in web browser. default file name myfile.txt
Using commons-fileupload.jar to Upload file
TBD
Using Struts1
File upload through Struts1:
In struts-config_1_3.dtd, we can find controller definition to control file uploading through struts1.*
struts-config/controller: |
By default struts 1 provide org.apache.struts.upload.CommonsMultipartRequestHandler to process file uploading transform. CommonsMultipartRequestHandler encapsulate apache-commons-fileupload for file uploading processing. If you want to know how CommonsMultipartRequestHandler manage file uploading or you want to implement your own MultipartRequestHandler, please refer to struts source code for that.
Your form should extends ActionForm and contains a FileForm named with same value as html:file/@name.
Then config your upload Action in struts-config.xml to map to this form-bean.
After that, we can use FormFile.getInputStream() to get file data and no need to care about file uploading processing.
File download through Struts1:
Struts 1 provide DownloadAction:
org.apache.struts.actions.DownloadAction.
Here is a snapshot of org.apache.struts.actions.DownloadAction.java:
public abstract class DownloadAction extends BaseAction {
|
So we should define an Action that extends DownloadAction and implement method:
StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response);
Using Struts2
Struts2 vs Struts1:
Since Struts2 realize webwork2 and provides different configuration as struts1. So it is more like a new MVC framework rather than upgrade of struts1. Here are some new features in struts2:
- Action should implement ActionSupport
- Each action's parameter fields will represent dedicated HTML/form data, so there is no need to define ActionForm (form-beans/form-bean in struts1) again.
- Struts2 introduce AOP interceptor and IOC (like /package/action/param)
- Configuration file changed a lot.
- ...
File uploading through struts2:
For file uploading, struts2 introduce three new parameters in Action to represent File information:
- File XXX: represent the File to be uploaded. XXX is the value of attribute: HTML/form/file/@name.
- String XXXFileName: represent the original file name of file XXX.
- String XXXContentType: represent the content type of file XXX.
If you want to upload a set of files, those three parameters should be defined as:
- File[] XXX: represent the File to be uploaded. XXX is the value of attribute: HTML/form/file/@name. All the file upload form should use same file/@name definition.
- String[] XXXFileName: represent the original file names of file XXX.
- String[] XXXContentType: represent the content types of files XXX.
So you should define your own upload Action as following:
- First extend ActionSupport and contain those three necessary parameters
- Then you can use File XXX to read data from InputStream.
Because in my current project, we do not use struts2, so I do not study the source code of struts2. But anyway, we can image there is a MultipartRequestHandler which will process file uploading and convert it into Action.XXX for us.
File Download through Struts2
About download, we can talk about it later.
But anyway, I am always thinking that even framework provide encapsulation of complex operation for us, but the kernel should always the same: send file data through Response OutputStream.
Attach file management in SOAP
TBD
发表评论
-
javax.naming.CommunicationException: remote side declared peer gone on this JVM.
2012-07-11 09:44 2379javax.naming.ServiceUnavailable ... -
Generate special format numbers
2012-04-27 00:06 941DecimalFormat df = new DecimalF ... -
Singleton Service in Weblogic Cluster
2012-03-21 00:12 712http://blog.csdn.net/mobicents/ ... -
Scheduled ThreadPool Executor suppressed or stopped after error happen
2012-03-20 16:54 1045ScheduledThreadPoolExecutor ... -
Bad version number in .class file
2012-01-27 00:35 896Bad version number in .class fi ... -
User Data Header in SMPP SUBMIT_SM
2012-01-25 22:30 2333SMPP optional Parameters for ... -
jQuery study
2011-12-28 00:44 0to be study -
Java is Pass-by-Value or Pass-by-Reference?
2011-12-19 19:18 688What's saved in Object Referenc ... -
java.util.Properties: a subclass of java.util.Hashtable
2011-12-13 06:57 777I met a problem this afternoon ... -
Jmock usage
2011-12-02 05:37 0Discuss how Jmock working. -
Oracle Index Usage
2011-12-15 05:26 628Like a hash mapping for record' ... -
AOP(2):AOP与动态代理JDK Proxy and Cglib Proxy
2011-05-12 16:20 1031使用动态代理(JDK Proxy 或者Cglib Proxy) ... -
AOP(1):应用中的几个小故事
2011-05-09 21:49 976I had heared about AOP almost 7 ... -
异步系统设计:push vs pull
2011-05-02 23:59 1139今天讨论问题时,有个同事说系统A是主动去系统B里“拿”消息,我 ... -
Velocity Usage
2011-04-28 22:52 1006You can find velocity mannua ... -
Java Regular Expression (Java正则表达式)
2011-04-23 06:58 935In current Project, we need to ... -
XML Parser:DOM + XPath
2011-04-23 06:30 1204There are many kinds of XML Par ... -
Manage zip content using Java APIs
2011-04-21 18:14 1042JDK provide a set of utils to c ... -
Beanshell: how and where to use beanshell
2011-04-21 00:33 2096How to use beanshell beansh ... -
OXM: JAXB2.0 in JDK1.6
2011-04-20 22:53 12421.1.1 JAXB 2.0: ObjectàXML ...
相关推荐
These technologies are explained in the context of real-world projects, such as an e-commerce application, a document management program, file upload and programmable file download, and an XML-based ...
- **File Upload and Download**: Practical examples of file upload and programmable file download functionalities are included, showcasing the use of third-party components from Brainy Software.com. ...
These technologies are explained in the context of real-world projects, such as an e-commerce application, a document management program, file upload and programmable file download, and an XML-based ...
它支持多种语言,包括Java,这使得Android开发者能够轻松地在应用中集成Dropbox功能。 在这个示例项目中,主要涉及以下几个关键知识点: 1. **OAuth 2.0授权**:为了访问Dropbox账户,应用需要通过OAuth 2.0协议...
本文将基于"upload_download_file.rar_IPUploadFileInfoVO"这个压缩包文件中的内容,详细讲解文件上传下载的实现原理和IPUploadFileInfoVO这个类在其中扮演的角色。 首先,让我们了解一下文件上传的基本流程。在...
Upload file to android application. Download file from android application. Support high concurrency. Dependencies Gradle compile 'com.yanzhenjie:andserver:1.0.3' Maven com.yanzhenjie andserver...
12)..Changed: VCL/CLX/FMX now will assign Application.OnException handler when low-level hooks are disabled EurekaLog 7.2 Hotfix 6 (7.2.6.0), 14-July-2015 1)....Added: csoCaptureDelphiExceptions ...
在IT行业中,Spring MVC是一个广泛使用的Java框架,用于构建Web应用程序。它提供了处理HTTP请求、渲染视图以及处理用户输入的强大功能。在这个场景下,我们关注的是Spring MVC如何实现文件的上传与下载功能,这对于...
6.3 Java Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 6.4 GML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...
在Java Web开发中,文件上传和下载是常见的功能需求,特别是在Spring MVC框架下。本教程将详细介绍如何利用`commons-fileupload`组件与Spring MVC结合实现文件上传,以及如何通过Servlet和`response`输出流实现文件...
在`web.xml`或Spring Boot的`application.properties`中配置`multipartResolver`: ```xml <!-- web.xml --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons....
### Java Spring Boot应用程序中实现文件上传和下载功能 在现代Web开发中,文件上传与下载是常见的需求之一。Spring Boot框架提供了简洁的方式帮助开发者轻松实现这些功能。本文将详细介绍如何在Spring Boot项目中...
Through in-depth research on the key points and challenges of building an online cloud storage system, the expected outcome is a system that allows users to register, upload files, share files, search...
例如,使用`swift upload <container_name>`命令可以上传文件到指定的容器,而`swift download <container_name>`则用于下载整个容器内的文件。 Web应用中,前端与后端的交互通常是通过Ajax实现的。Ajax...
Instructions on how to download and install the JavaMail API are contained in the course. In addition, you will need a development environment such as the JDK 1.1.6+ or the Java 2 Platform, Standard...
Getting started with Spring ...Chapter 13 – More Spring Web MVC – internationalization, file upload and asynchronous request processing Chapter 14 – Securing applications using Spring Security
打开src/main/resources/application.properties文件,然后将属性file.upload-dir更改为要存储上载文件的路径。 file.upload-dir=/Users/callicoder/uploads 2.使用maven运行应用 cd spring-boot-file-upload-...
在`application.properties`中添加如下配置: ```properties # 配置文件上传路径 spring.servlet.multipart.location=uploads/ # 设置最大上传文件大小(单位:MB) spring.servlet.multipart.max-file-size=5MB # ...