三种方式上传文件-Java

简介:

前言:负责,因为该项目他(jetty嵌入式开始SpringMvc)实现文件上传的必要性,并拥有java文件上传这一块还没有被曝光。并 Http 更多晦涩协议。因此,这种渐进的方式来学习和实践上载文件的原则。

该博客侧重于实践。


一.Http协议原理简单介绍

    HTTP是一个属于应用层的面向对象的协议。因为其简捷、高速的方式,适用于分布式超媒体信息系统。它于1990年提出,经过几年的使用与发展,得到不断地完好和扩展。眼下在WWW中使用的是HTTP/1.0的第六版,HTTP/1.1的规范化工作正在进行之中。并且HTTP-NG(Next Generation of HTTP)的建议已经提出。

    简单来说。就是一个基于应用层的通信规范:两方要进行通信。大家都要遵守一个规范,这个规范就是HTTP协议。

 1.特点:

  (1)支持客户/server模式。

  (2)简单高速:客户向server请求服务时,仅仅需传送请求方法和路径。请求方法经常使用的有GET、HEAD、POST。每种方法规定了客户与server联系的类型不同。

因为HTTP协议简单,使得HTTPserver的程序规模小。因而通信速度非常快。


  (3)灵活:HTTP同意传输随意类型的数据对象。正在传输的类型由Content-Type加以标记。

  (4)无连接:无连接的含义是限制每次连接仅仅处理一个请求。

server处理完客户的请求。并收到客户的应答后,即断开连接。採用这样的方式能够节省传输时间。

  (5)无状态:HTTP协议是无状态协议。无状态是指协议对于事务处理没有记忆能力。

缺少状态意味着假设兴许处理须要前面的信息,则它必须重传。这样可能导致每次连接传送的数据量增大。

还有一方面,在server不须要先前信息时它的应答就较快。


  注意:当中(4)(5)是面试中经常使用的面试题。

尽管HTTP协议(应用层)是无连接。无状态的,但其所依赖的TCP协议(传输层)却是常连接、有状态的。而TCP协议(传输层)又依赖于IP协议(网络层)。


2.HTTP消息的结构

 (1)Request 消息分为3部分,第一部分叫请求行。 第二部分叫http header消息头, 第三部分是body正文。header和body之间有个空行。 结构例如以下图


 (2)Response消息的结构, 和Request消息的结构基本一样。 相同也分为三部分。第一部分叫request line状态行, 第二部分叫request header消息体。第三部分是body正文, header和body之间也有个空行,  结构例如以下图



以下是使用Fiddler捕捉请求baidu的Request消息机构和Response消息机构:


由于没有输入不论什么表单信息,故request的消息正文为空,大家能够找一个登录的页面试试看。


  先到这里,HTTP协议的知识网上非常丰富,在这里就不再熬述了。


二.文件上传的三种实现

1.Jsp/servlet 实现文件上传

 这是最常见也是最简单的方式

 (1)实现文件上传的Jsp页面

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h2>File upload demo</h2>
<form action="fileload"  method="post" enctype="multipart/form-data">
  <input type="file" name="filename" size="45"><br>
  <input type="submit" name="submit" value="submit">
</form>
</body>
</html>

 (2)负责接文件的FileUploadServlet

import java.io.File;
import java.io.FileOutputStream;
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;

import org.apache.log4j.Logger;

// @WebServlet(name = "FileLoadServlet", urlPatterns = {"/fileload"})
public class FileLoadServlet extends HttpServlet {
	
	private static Logger logger = Logger.getLogger(FileLoadServlet.class);

	/**
	 * 
	 */
	private static final long serialVersionUID = 1302377908285976972L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info("------------ FileLoadServlet ------------");
		
		if (request.getContentLength() > 0) {
			
	           InputStream inputStream = null;
	           FileOutputStream outputStream = null;
	           
			try {
				
				inputStream = request.getInputStream();
				// 给新文件拼上时间毫秒。防止重名
				long now = System.currentTimeMillis();
				File file = new File("c:/", "file-" + now + ".txt");
				file.createNewFile();
				
				outputStream = new FileOutputStream(file);
				
				byte temp[] = new byte[1024];
				int size = -1;
				while ((size = inputStream.read(temp)) != -1) { // 每次读取1KB,直至读完
					outputStream.write(temp, 0, size);
				}
				
				logger.info("File load success.");
			} catch (IOException e) {
				logger.warn("File load fail.", e);
				request.getRequestDispatcher("/fail.jsp").forward(request, response);
			} finally {
				outputStream.close();
				inputStream.close();
			}
		}
		
		request.getRequestDispatcher("/succ.jsp").forward(request, response);
	}
	
}
 

  FileUploadServlet的配置。推荐採用servlet3.0注解的方式更方便

  <servlet>
    <servlet-name>FileLoadServlet</servlet-name>
    <servlet-class>com.juxinli.servlet.FileLoadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>FileLoadServlet</servlet-name>
    <url-pattern>/fileload</url-pattern>
  </servlet-mapping>

 (3)执行效果

点击"submit"



页面转向文件上传成功的页面。再去C盘看看,发现多了一个文件:file-1433417127748.txt,这个就是刚上传的文件



我们打开看看,发现和原来的文本有些不一样

             


结合前面讲的HTTP协议的消息结构,不难发现这些文本就是去掉"请求头"后的"Request消息体"。

所以,假设要得到与上传文件一致的文本。还须要一些字符串操作。这些就留给大家了。

另外。大家能够试试一个Jsp页面上传多个文件,会有不一样的精彩哦o(∩_∩)o ,不解释。


2.模拟Post请求/servlet 实现文件上传

刚才我们是使用Jsp页面来上传文件。假如client不是webapp项目呢,显然刚才的那种方式有些捉襟见衬了。

这里我们换种思路,既然页面上通过点击能够实现文件上传,为何不能通过HttpClient来模拟浏览器发送上传文件的请求呢。关于HttpClient ,大家能够自己去了解。

 (1)还是这个项目。启动servlet服务


 (2)模拟请求的FileLoadClient

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.log4j.Logger;

public class FileLoadClient {
	
	private static Logger logger = Logger.getLogger(FileLoadClient.class);
	
	public static String fileload(String url, File file) {
		String body = "{}";
		
		if (url == null || url.equals("")) {
			return "參数不合法";
		}
		if (!file.exists()) {
			return "要上传的文件名称不存在";
		}
		
		PostMethod postMethod = new PostMethod(url);
		
        try {
        	
            // FilePart:用来上传文件的类,file即要上传的文件
            FilePart fp = new FilePart("file", file);
            Part[] parts = { fp };

            // 对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装
            MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
            postMethod.setRequestEntity(mre);
            
            HttpClient client = new HttpClient();
            // 因为要上传的文件可能比較大 , 因此在此设置最大的连接超时时间
            client.getHttpConnectionManager().getParams() .setConnectionTimeout(50000);
            
            int status = client.executeMethod(postMethod);
            if (status == HttpStatus.SC_OK) {
                InputStream inputStream = postMethod.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
                
                StringBuffer stringBuffer = new StringBuffer();
                String str = "";
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }
                
                body = stringBuffer.toString();
                
            } else {
            	body = "fail";
            }
        } catch (Exception e) {
            logger.warn("上传文件异常", e);
        } finally {
            // 释放连接
            postMethod.releaseConnection();
        }
		
		return body;
	}
	
	
	public static void main(String[] args) throws Exception {
		String body = fileload("http://localhost:8080/jsp_upload-servlet/fileload", new File("C:/1111.txt"));
		System.out.println(body);
	}
	
}


 (3)在Eclipse中执行FileLoadClient程序来发送请求,执行结果:

<html><head>  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body><h2>File upload success</h2><a href="index.jsp">return</a></body></html>
打印了:文件上传成功的succ.jsp页面




有没有发现什么,是不是和前面Jsp页面上传的结果类似?对的。还是去掉"请求头"后的"Request消息体"。


这样的方式也非常easy。负责接收文件的FileUploadServlet没有变。仅仅要在client把文件读取到流中,然后模拟请求servlet即可了。


3.模拟Post请求/Controller(SpringMvc)实现文件上传

最终到第三种方式了,主要难点在于搭建maven+jetty+springmvc环境,接收文件的service和模拟请求的client 和上面相似。


 (1)模拟请求的FileLoadClient未变

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.log4j.Logger;

public class FileLoadClient {
	
	private static Logger logger = Logger.getLogger(FileLoadClient.class);
	
	public static String fileload(String url, File file) {
		String body = "{}";
		
		if (url == null || url.equals("")) {
			return "參数不合法";
		}
		if (!file.exists()) {
			return "要上传的文件名称不存在";
		}
		
		PostMethod postMethod = new PostMethod(url);
		
        try {
        	
            // FilePart:用来上传文件的类,file即要上传的文件
            FilePart fp = new FilePart("file", file);
            Part[] parts = { fp };

            // 对于MIME类型的请求。httpclient建议全用MulitPartRequestEntity进行包装
            MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
            postMethod.setRequestEntity(mre);
            
            HttpClient client = new HttpClient();
            // 因为要上传的文件可能比較大 , 因此在此设置最大的连接超时时间
            client.getHttpConnectionManager().getParams() .setConnectionTimeout(50000);
            
            int status = client.executeMethod(postMethod);
            if (status == HttpStatus.SC_OK) {
                InputStream inputStream = postMethod.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
                
                StringBuffer stringBuffer = new StringBuffer();
                String str = "";
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }
                
                body = stringBuffer.toString();
                
            } else {
            	body = "fail";
            }
        } catch (Exception e) {
            logger.warn("上传文件异常", e);
        } finally {
            // 释放连接
            postMethod.releaseConnection();
        }
		
		return body;
	}
	
	
	public static void main(String[] args) throws Exception {
		String body = fileload("http://localhost:8080/fileupload/upload", new File("C:/1111.txt"));
		System.out.println(body);
	}

 (2)servlet换为springMvc中的Controller

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/fileupload")
public class FileUploadService {
	
	private Logger logger = Logger.getLogger(FileUploadService.class);
	
	@RequestMapping(consumes = "multipart/form-data", value = "/hello", method = RequestMethod.GET)
	public void hello(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		response.getWriter().write("Hello, jetty server start ok.");
	}
	
	@RequestMapping(consumes = "multipart/form-data", value = "/upload", method = RequestMethod.POST)
	public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String result = "";
		
		if (request.getContentLength() > 0) {
			
	           InputStream inputStream = null;
	           FileOutputStream outputStream = null;
	           
			try {
				inputStream = request.getInputStream();
				// 给新文件拼上时间毫秒,防止重名
				long now = System.currentTimeMillis();
				File file = new File("c:/", "file-" + now + ".txt");
				file.createNewFile();
				
				outputStream = new FileOutputStream(file);
				
				byte temp[] = new byte[1024];
				int size = -1;
				while ((size = inputStream.read(temp)) != -1) { // 每次读取1KB。直至读完
					outputStream.write(temp, 0, size);
				}
				
				logger.info("File load success.");
				result = "File load success.";
			} catch (IOException e) {
				logger.warn("File load fail.", e);
				result = "File load fail.";
			} finally {
				outputStream.close();
				inputStream.close();
			}
		}
		
		response.getWriter().write(result);
	}

}

 (3)启动jetty的核心代码,在Eclipse里面右键能够启动。也能够把项目打成jar报启动

import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.webapp.WebAppContext;

public class Launcher {
	
	private static Logger logger = Logger.getLogger(Launcher.class);
	
	private static final int PORT = 8080;
	private static final String WEBAPP = "src/main/webapp";
	private static final String CONTEXTPATH = "/";
	private static final String DESCRIPTOR = "src/main/webapp/WEB-INF/web.xml";


	/*
	 * 创建 Jetty Server。指定其端口、web文件夹、根文件夹、web路径
	 * @param port
	 * @param webApp
	 * @param contextPath
	 * @param descriptor
	 * @return Server
	 */
	public static Server createServer(int port, String webApp, String contextPath, String descriptor) {
		Server server = new Server();
		//设置在JVM退出时关闭Jetty的钩子
		//这样就能够在整个功能測试时启动一次Jetty,然后让它在JVM退出时自己主动关闭
		server.setStopAtShutdown(true);
		
		ServerConnector connector = new ServerConnector(server); 
		connector.setPort(port); 
		//解决Windows下反复启动Jetty不报告端口冲突的问题
		//在Windows下有个Windows + Sun的connector实现的问题,reuseAddress=true时反复启动同一个端口的Jetty不会报错
		//所以必须设为false,代价是若上次退出不干净(比方有TIME_WAIT),会导致新的Jetty不能启动,但权衡之下还是应该设为False
		connector.setReuseAddress(false);
		server.setConnectors(new Connector[]{connector});
		
		WebAppContext webContext = new WebAppContext(webApp, contextPath);
		webContext.setDescriptor(descriptor);
		// 设置webapp的位置
		webContext.setResourceBase(webApp);
		webContext.setClassLoader(Thread.currentThread().getContextClassLoader());
				
		server.setHandler(webContext);
		
		return server;
	}
	
	/**
	 * 启动jetty服务
	 * 
	 */
	public void startJetty() {
		final Server server = Launcher.createServer(PORT, WEBAPP, CONTEXTPATH, DESCRIPTOR);
		
		try {
			server.start();
			server.join();
			
		} catch (Exception e) {
			logger.warn("启动 jetty server 失败", e);
			System.exit(-1);
		}
	}
	
	public static void main(String[] args) {
		
		(new Launcher()).startJetty();
		// jetty 启动后的測试url
		// http://localhost:8080/fileupload/hello
	}
	
}


springMvc的配置不贴了,大家能够下载源代码下来看。


 (4)执行效果

执行 Launcher 后能够訪问http://localhost:8080/fileupload/hello 查看jetty+springMvc启动是否正常



执行 FileLoadClient后打印的日志:



说明文件上传成功




附源代码下载:

jsp_upload-servlet项目:(1).Jsp/servlet 实现文件上传  (2).模拟Post请求/servlet 实现文件上传

jetty_upload-springmvc项目:(3).模拟Post请求/Controller(SpringMvc)实现文件上传

csdn下载地址

文件上传的三种方式-Java


GitHub下载地址

https://github.com/leonzm/jsp_upload-servlet.git
https://github.com/leonzm/jetty_upload-springmvc.git


时间比較仓促,可能有不正确或者不完好的地方,大家能够提出来一起学习。


參考&引用:

浅析HTTP协议
http://www.cnblogs.com/gpcuster/archive/2009/05/25/1488749.html

HTTP协议具体解释
http://blog.csdn.net/gueter/article/details/1524447

HTTP 协议具体解释
http://kb.cnblogs.com/page/130970/

HttpClient学习整理
http://www.cnblogs.com/ITtangtang/p/3968093.html


TCP/IP、Http、Socket的差别
http://jingyan.baidu.com/article/08b6a591e07ecc14a80922f1.html


Spring MVC 教程,高速入门,深入分析
http://yinny.iteye.com/blog/1926799

jetty启动以及嵌入式启动
http://yinny.iteye.com/blog/1926799

启动jetty方式
http://hbiao68.iteye.com/blog/2111007

Jetty较有用引导程序
http://www.xuebuyuan.com/1400368.html



版权声明:本文博主原创文章。博客,未经同意不得转载。







本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/4776833.html,如需转载请自行联系原作者


相关文章
|
1月前
|
Java
有关Java发送邮件信息(支持附件、html文件模板发送)
有关Java发送邮件信息(支持附件、html文件模板发送)
31 1
|
1月前
|
Java
java中替换文件内容
java中替换文件内容
14 1
|
1月前
|
Java API
Java中文件与输入输出
Java中文件与输入输出
|
1月前
|
Java
java实现遍历树形菜单方法——映射文件VoteTree.hbm.xml
java实现遍历树形菜单方法——映射文件VoteTree.hbm.xml
10 0
|
1月前
|
Java
java程序导出堆文件
java程序导出堆文件
|
1月前
|
SQL Oracle Java
sql文件批处理程序-java桌面应用
sql文件批处理程序-java桌面应用
25 0
|
1月前
|
存储 Java 文件存储
如何用 Java 压缩 ZIP 文件?
【2月更文挑战第21天】
35 1
|
1月前
|
弹性计算 前端开发 小程序
微信小程序上传文件至阿里云OSS直传(java后端签名+前端直传)
当前的通用文件上传方式是通过前端上传到服务器,再由服务器转存至对象存储。这种方式在处理小文件时效率尚可,但大文件上传因受限于服务器带宽,速度较慢。例如,一个100MB的文件在5Mbps带宽的阿里云ECS上上传至服务器需160秒。为解决此问题,可以采用后端签名的方式,使微信小程序直接上传文件到阿里云OSS,绕过服务器中转。具体操作包括在JAVA后端引入相关依赖,生成签名,并在微信小程序前端使用这个签名进行文件上传,注意设置正确的请求头和formData参数。这样能提高大文件上传的速度。
|
5天前
|
Java 关系型数据库 MySQL
Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
【4月更文挑战第12天】Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
33 3
|
29天前
|
Java Spring
上传文件出现 aximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.
上传文件出现 aximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.
11 0