java是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE, JavaME, JavaSE)的总称。本站提供基于Java框架struts,spring,hibernate等的桌面应用、web交互及移动终端的开发技巧与资料

保持永久学习的心态,将成就一个优秀的你,来 继续搞起java知识。

JSP,Servlet文件上传(不使用任何依赖JAR包),有需要的朋友可以参考下。

JAVA的文件上传大多依赖commons-io-xx.jar和commons-fileupload-xx.jar或者依赖第三方的框架,可是自己觉得还是太臃肿了。

以下是JSP源码,同时把该内容copy到Servlet中同样可以使用

<%@page import=&quot;java.io.ByteArrayOutputStream&quot;%>
<%@page import=&quot;java.io.PrintWriter&quot;%>
<%@page import=&quot;java.io.FileNotFoundException&quot;%>
<%@page import=&quot;java.io.FileOutputStream&quot;%>
<%@page import=&quot;java.io.IOException&quot;%>
<%@page import=&quot;java.io.StringReader&quot;%>
<%@page import=&quot;java.io.BufferedReader&quot;%>
<%@page import=&quot;java.io.File&quot;%>
<%@page import=&quot;java.io.InputStream&quot;%>
<%@page language=&quot;java&quot; contentType=&quot;text/html; charset=UTF-8&quot; pageEncoding=&quot;UTF-8&quot;%>
<%--
@author com.love
实现单文件上传
@date 2015 12 03
--%>
<%!
//系统中文本换行符
public static String END_OF_HEADER_SEPARATOR = System.getProperty(&quot;line.separator&quot;)+System.getProperty(&quot;line.separator&quot;);
//提取上传的文件头信息
private MultipartHeaderInfoBean extractMultipartHeaderInfo(String _header_text) throws IOException {
	BufferedReader reader = new BufferedReader(new StringReader(_header_text));
	String multipartDelimiter, fileName, contentType,lineRead;
	if ((lineRead = reader.readLine()) != null) {
		//读取的第一行是一个分割符
		multipartDelimiter = lineRead;
		if ((lineRead = reader.readLine()) != null) {
			//读取的第二行为:Content-Disposition: form-data; name=&quot;file1&quot;; filename=&quot;320_442.png&quot;
			fileName = new File(lineRead.split(&quot;;&quot;)[2].split(&quot;=&quot;)[1]
					.replace(&#39;&quot;&#39;, &#39; &#39;).trim()).getName();
			//以上为获取filename
			if ((lineRead = reader.readLine()) != null) {
				//第三行为:Content-Type: image/png
				contentType = lineRead.split(&quot;:&quot;)[1].trim();
				//返回上传文件头的实体类
				return new MultipartHeaderInfoBean(multipartDelimiter,fileName, contentType);
			}
		}
	}
	return null;
}
//提取的上传文件信息头Bean
class MultipartHeaderInfoBean {
	//文件分隔符
	private String multipartDelimiter;
	//文件名
	private String originalFileName;
	//文件的 content type
	private String contentType;
	
	public MultipartHeaderInfoBean(String _multipart_delimiter,
			String _original_file_name, String _content_type) {
		multipartDelimiter = _multipart_delimiter;
		originalFileName = _original_file_name;
		contentType = _content_type;
	}
	
}
%>
<%
if(request.getMethod().equals(&quot;POST&quot;)){
	InputStream inputStream = request.getInputStream();
	if (inputStream.available()!=-1) {
		//判断文件大小
		System.out.println(request.getContentLength());
		if (request.getContentLength() > 500000) {
			 System.err.println(&quot;DEBUG - ERROR file length is too large&quot;);
			return;
		}
		//建立缓冲区
		ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(request.getContentLength());
		if (inputStream != null) {
			int i =0;
	        byte [] b = new byte[2048];
	        while((i = inputStream.read(b))!= -1){
	             byteOutput.write(b, 0, i);
	        }
	    }
		//字节数组
		byte requestContent [] =byteOutput.toByteArray();
		//转为字符串
		String requestContentAsString =new String(requestContent);
		//计算报头分割现的结束位置
		int endOfHeaderIndex = requestContentAsString.indexOf(END_OF_HEADER_SEPARATOR);
		
		//获取报头所携带的文件信息
		MultipartHeaderInfoBean headerBean = extractMultipartHeaderInfo(
				requestContentAsString.substring(0, endOfHeaderIndex));
		//检查文件的扩展名
		if (headerBean.originalFileName.toLowerCase().indexOf(&quot;.jpg&quot;) >= 0) {
			System.err.println(&quot;DEBUG - ERROR JPG extension not allowed&quot;);
			return;
		}
		//检查文件的content type
		if (&quot;video/mpeg&quot;.equals(headerBean.contentType)) {
			System.err.println(&quot;DEBUG - ERROR content type is invalid&quot;);
			return;
		}
		//获取文件内容
		int beginIndex = endOfHeaderIndex + END_OF_HEADER_SEPARATOR.length();
		
		String fileContent = requestContentAsString.substring(beginIndex,requestContentAsString.length());
		//System.out.println(&quot;头|&quot;+requestContentAsString.substring(beginIndex,requestContentAsString.length())+&quot;|尾&quot;);
		
		//把文件写到本地
		FileOutputStream fileOut = new FileOutputStream(new File(
				&quot;D:\\Upload\\Basic-&quot; + headerBean.originalFileName));
		//计算长度
		int start =requestContentAsString.substring(0,beginIndex).getBytes().length;
		int endIndex = requestContentAsString.indexOf(headerBean.multipartDelimiter,beginIndex);
		int length = requestContentAsString.substring(beginIndex,endIndex).getBytes().length;
		//wirte
		fileOut.write(requestContent,start,length);
		fileOut.flush();
		fileOut.close();
		
		//out
		PrintWriter pw = response.getWriter();
		pw.print(&quot;file upload success!!!&quot;);
		pw.close();
	}else{
		System.err.println(&quot;DEBUG - ERROR file can not be empty&quot;);
	}	
}
%>
<!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;>
<html>
<head>
<meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;>
<title>Test File Upload</title>
</head>
<body>
<h1>Test File upload</h1>
<form action=&quot;upload.jsp&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;>
	<input type=&quot;file&quot; name=&quot;file1&quot; /><br>
	<input type=&quot;submit&quot; value=&quot;上传&quot; />
</form>
</body>
</html>

感谢观看,努力学习中.....

因为水平有限,难免有疏忽或者不准确的地方,希望大家能够直接指出来,我会及时改正。一切为了知识的分享。

后续会有更多的精彩的内容分享给大家。