新建一个index.jsp,代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script>
function check(source) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
document.getElementById("filepath").value = getFullPath(source);
document.getElementById("fileSize").innerHTML = "文件大小为"
+ fso.GetFile(getFullPath(source)).size + "kb";
var pos = getFullPath(source).lastIndexOf("\\");
var full = getFullPath(source).substring(pos + 1);
pos = full.lastIndexOf(".");
document.getElementById("fileName").innerHTML = "文件名字为"
+ full.substring(0, pos);
document.getElementById("fileType").innerHTML = "文件类型为"
+ full.substring(pos + 1);
}
// 得到文件的完整路径
function getFullPath(obj) {
if (obj) {
//ie
if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
obj.select();
return document.selection.createRange().text;
}
//firefox
else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
if (obj.files) {
return obj.files.item(0).getAsDataURL();
}
return obj.value;
}
return obj.value;
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File UpLoad</title>
</head>
<body>
<form action="upload.jsp" method="post">
<input type="file" name="file" id="file" onchange="check(this)">
<br> <input type="text" name="filepath" id="filepath">
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<br> <input type="submit" value="上传">
</form>
</body>
</html>
在同一目录下,新建upload.jsp,代码如下:
<%@page import="java.io.FileOutputStream"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.io.File"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
// 设置请求内容和响应内容的编码
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
// 获取要提交的文件,与index.jsp form表单的file的name相同
String filepath = request.getParameter("filepath");
File oldFile = new File(filepath);
InputStream inputStream = new FileInputStream(oldFile);
File newFile = new File("1.jpg");
FileOutputStream fileOutputStream = new FileOutputStream(newFile);
byte[] bytes = new byte[1024];
int length = 0;
while ((length = inputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, length);
}
inputStream.close();
fileOutputStream.close();
out.print("上传成功\n");
out.print("上传文件的路径为:" + newFile.getAbsolutePath());
%>
即实现的文件的上传。
效果图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3WwhSQJc-1615947699308)(https://img-blog.youkuaiyun.com/20160216230221806)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qe2FZ8wP-1615947699312)(https://img-blog.youkuaiyun.com/20160216230229010)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-f1waGfPN-1615947699314)(https://img-blog.youkuaiyun.com/20160216230236604)]
工程下载地址:点击下载