jsp文件上传与下载实例代码
网络编程 2021-07-05 11:23www.168986.cn编程入门
文件上传与下载在javaWeb开发中还是比较常见的,于是分享下实用案例,感兴趣的朋友可以参考下哈,希望对你有所帮助
文件上传
public class UploadServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
SmartUpload myupload = new SmartUpload();
ServletConfig config = getServletConfig();
myupload.initialize(config,req,resp);
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
out.println("<h2>处理上传的文件</h2>");
out.println("<hr>");
try {
myupload.setMaxFileSize(10241024);
myupload.setTotalMaxFileSize(510241024);
myupload.setAllowedFilesList("doc,txt,jpg,gif");
myupload.setDeniedFilesList("exe,bat,jsp,htm,html");
myupload.upload();//上传文件,此项是必须的
int count = myupload.getFiles().getCount();
Request myRequest = myupload.getRequest();
String rndFilename,fileExtName,fileName,filePathName;
Date dt = null;
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
//一一提取上传文件信息,可保持文件
for(int i = 0; i < count; i++){
File file = myupload.getFiles().getFile(i);
if(file.isMissing())
continue;
fileName = new String(file.getFileName().getBytes(),"utf-8");//获取文件名
filePathName = new String(file.getFilePathName().getBytes(),"utf-8");
fileExtName = file.getFileExt();
dt = new Date(System.currentTimeMillis());
Thread.sleep(100);
rndFilename = fmt.format(dt)+i+"."+fileExtName;
out.println("第"+(i+1)+"个文件的文件信息<br>");
out.println(" 文件名为"+fileName+"<br>");
out.println(" 文件扩展名为"+fileExtName+"<br>");
out.println(" 文件全名"+filePathName+"<br>");
out.println(" 文件大小"+file.getSize()/1024+"kb<br>");
//创建文件保存位置
ServletContext context = req.getServletContext();
String savePath = context.getRealPath("/upload/");
java.io.File folder = new java.io.File(savePath);
if(!folder.exists()){
folder.mkdirs();
}
out.println(" 文件保存路径"+savePath);
file.saveAs(savePath+"/"+rndFilename,SmartUpload.SAVE_PHYSICAL);
}
} catch (Exception e) {
out.println("文件上传失败!!!!");
e.printStackTrace();
}
out.flush();
out.close();
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import=".jspsmart.upload." %>
<%
//设定请求编码方式,否则遇到中文就会乱码
request.setCharacterEncoding("utf-8");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://.w3./TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传文件实例</title>
<script type="text/javascript" src="js/jquery-1.8.1.js"></script>
<script type="text/javascript">
$(function(){
$("#number").change(function(){
var number = $("#number").attr("value");
$("#files").html("");
for(var i = 0; i < number; i++){
$("#files").append("<input type='file' name='file''"+i+"'><br/>");
}
});
});
</script>
</head>
<body>
<h2>上传文件实例</h2>
请选择上传文件数量
<select id="number">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<div id="files"></div>
<input type="submit" value="提交"/>
</form>
</body>
</html>
文件下载
<%
response.setContentType("application/x-download");//设置为下载application/x-download
String filedownload = "/要下载的文件名";//即将下载的文件的相对路径
String filedisplay = "最终要显示给用户的保存文件名";//下载文件时显示的文件保存名称
String filenamedisplay = URLEncoder.encode(filedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filedisplay);
try
{
RequestDispatcher dis = application.getRequestDispatcher(filedownload);
if(dis!= null)
{
dis.forward(request,response);
}
response.flushBuffer();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
}
%>
代码如下:
public class UploadServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
SmartUpload myupload = new SmartUpload();
ServletConfig config = getServletConfig();
myupload.initialize(config,req,resp);
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
out.println("<h2>处理上传的文件</h2>");
out.println("<hr>");
try {
myupload.setMaxFileSize(10241024);
myupload.setTotalMaxFileSize(510241024);
myupload.setAllowedFilesList("doc,txt,jpg,gif");
myupload.setDeniedFilesList("exe,bat,jsp,htm,html");
myupload.upload();//上传文件,此项是必须的
int count = myupload.getFiles().getCount();
Request myRequest = myupload.getRequest();
String rndFilename,fileExtName,fileName,filePathName;
Date dt = null;
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
//一一提取上传文件信息,可保持文件
for(int i = 0; i < count; i++){
File file = myupload.getFiles().getFile(i);
if(file.isMissing())
continue;
fileName = new String(file.getFileName().getBytes(),"utf-8");//获取文件名
filePathName = new String(file.getFilePathName().getBytes(),"utf-8");
fileExtName = file.getFileExt();
dt = new Date(System.currentTimeMillis());
Thread.sleep(100);
rndFilename = fmt.format(dt)+i+"."+fileExtName;
out.println("第"+(i+1)+"个文件的文件信息<br>");
out.println(" 文件名为"+fileName+"<br>");
out.println(" 文件扩展名为"+fileExtName+"<br>");
out.println(" 文件全名"+filePathName+"<br>");
out.println(" 文件大小"+file.getSize()/1024+"kb<br>");
//创建文件保存位置
ServletContext context = req.getServletContext();
String savePath = context.getRealPath("/upload/");
java.io.File folder = new java.io.File(savePath);
if(!folder.exists()){
folder.mkdirs();
}
out.println(" 文件保存路径"+savePath);
file.saveAs(savePath+"/"+rndFilename,SmartUpload.SAVE_PHYSICAL);
}
} catch (Exception e) {
out.println("文件上传失败!!!!");
e.printStackTrace();
}
out.flush();
out.close();
}
}
代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import=".jspsmart.upload." %>
<%
//设定请求编码方式,否则遇到中文就会乱码
request.setCharacterEncoding("utf-8");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://.w3./TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传文件实例</title>
<script type="text/javascript" src="js/jquery-1.8.1.js"></script>
<script type="text/javascript">
$(function(){
$("#number").change(function(){
var number = $("#number").attr("value");
$("#files").html("");
for(var i = 0; i < number; i++){
$("#files").append("<input type='file' name='file''"+i+"'><br/>");
}
});
});
</script>
</head>
<body>
<h2>上传文件实例</h2>
请选择上传文件数量
<select id="number">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<div id="files"></div>
<input type="submit" value="提交"/>
</form>
</body>
</html>
文件下载
代码如下:
<%
response.setContentType("application/x-download");//设置为下载application/x-download
String filedownload = "/要下载的文件名";//即将下载的文件的相对路径
String filedisplay = "最终要显示给用户的保存文件名";//下载文件时显示的文件保存名称
String filenamedisplay = URLEncoder.encode(filedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filedisplay);
try
{
RequestDispatcher dis = application.getRequestDispatcher(filedownload);
if(dis!= null)
{
dis.forward(request,response);
}
response.flushBuffer();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
}
%>
编程语言
- 如何快速学会编程 如何快速学会ug编程
- 免费学编程的app 推荐12个免费学编程的好网站
- 电脑怎么编程:电脑怎么编程网咯游戏菜单图标
- 如何写代码新手教学 如何写代码新手教学手机
- 基础编程入门教程视频 基础编程入门教程视频华
- 编程演示:编程演示浦丰投针过程
- 乐高编程加盟 乐高积木编程加盟
- 跟我学plc编程 plc编程自学入门视频教程
- ug编程成航林总 ug编程实战视频
- 孩子学编程的好处和坏处
- 初学者学编程该从哪里开始 新手学编程从哪里入
- 慢走丝编程 慢走丝编程难学吗
- 国内十强少儿编程机构 中国少儿编程机构十强有
- 成人计算机速成培训班 成人计算机速成培训班办
- 孩子学编程网上课程哪家好 儿童学编程比较好的
- 代码编程教学入门软件 代码编程教程