JSP,Servlet文件上传(不使用任何依赖JAR包)
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="java.io.ByteArrayOutputStream"%>
<%@page import="java.io.PrintWriter"%>
<%@page import="java.io.FileNotFoundException"%>
<%@page import="java.io.FileOutputStream"%>
<%@page import="java.io.IOException"%>
<%@page import="java.io.StringReader"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.io.File"%>
<%@page import="java.io.InputStream"%>
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%--
@author com.love
实现单文件上传
@date 2015 12 03
--%>
<%!
//系统中文本换行符
public static String END_OF_HEADER_SEPARATOR = System.getProperty("line.separator")+System.getProperty("line.separator");
//提取上传的文件头信息
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="file1"; filename="320_442.png"
fileName = new File(lineRead.split(";")[2].split("=")[1]
.replace('"', ' ').trim()).getName();
//以上为获取filename
if ((lineRead = reader.readLine()) != null) {
//第三行为:Content-Type: image/png
contentType = lineRead.split(":")[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("POST")){
InputStream inputStream = request.getInputStream();
if (inputStream.available()!=-1) {
//判断文件大小
System.out.println(request.getContentLength());
if (request.getContentLength() > 500000) {
System.err.println("DEBUG - ERROR file length is too large");
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(".jpg") >= 0) {
System.err.println("DEBUG - ERROR JPG extension not allowed");
return;
}
//检查文件的content type
if ("video/mpeg".equals(headerBean.contentType)) {
System.err.println("DEBUG - ERROR content type is invalid");
return;
}
//获取文件内容
int beginIndex = endOfHeaderIndex + END_OF_HEADER_SEPARATOR.length();
String fileContent = requestContentAsString.substring(beginIndex,requestContentAsString.length());
//System.out.println("头|"+requestContentAsString.substring(beginIndex,requestContentAsString.length())+"|尾");
//把文件写到本地
FileOutputStream fileOut = new FileOutputStream(new File(
"D:\\Upload\\Basic-" + 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("file upload success!!!");
pw.close();
}else{
System.err.println("DEBUG - ERROR file can not be empty");
}
}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test File Upload</title>
</head>
<body>
<h1>Test File upload</h1>
<form action="upload.jsp" method="post" enctype="multipart/form-data">
<input type="file" name="file1" /><br>
<input type="submit" value="上传" />
</form>
</body>
</html>
感谢观看,努力学习中.....
因为水平有限,难免有疏忽或者不准确的地方,希望大家能够直接指出来,我会及时改正。一切为了知识的分享。
后续会有更多的精彩的内容分享给大家。
支付宝扫一扫
微信扫一扫
