JSP上传文件(如图片)的最简单的Demo

本文介绍了一个简单的图片上传组件实现,包括文件大小限制、文件类型检查、路径生成和保存操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<%@ page contentType="text/html; charset=gb2312"%>
<%@ page import="com.jspsmart.upload.*"%>


<%@ page import="java.util.Calendar,java.io.File"%>
<%
request.setCharacterEncoding("gb2312");

try{
SmartUpload su = new SmartUpload(); /// 上传文件组件
long file_max_size = 4000000;
su.initialize(pageContext);// 上传初始化
su.upload();
// 将上传文件全部保存到指定目录
String temp="upload/images";
//创建文件夹使用绝对路径
String uploadPath =request.getRealPath("/")+temp;
//如果文件夹不存在,则创建此文件夹
if(!new File(uploadPath).isDirectory()){
new File(uploadPath).mkdirs();
}
Files files=su.getFiles();
//得到上传的文件
com.jspsmart.upload.File file = su.getFiles().getFile(0);

if(file.isMissing()){
System.out.println("missing");
}
String postfix="."+file.getFileExt();
//为上传的文件起别名
System.out.println("后缀名是:" + postfix);
if(!postfix.equals(".jpg")){
%>
<script type="text/javascript">
alert("不支持此图片格式");
</script>
<%
}else{
String fileName = "test";
//这个就是可以得到图片的路径了
String strtemp=uploadPath+"/"+ fileName + postfix;
System.out.println(strtemp);
file.saveAs(strtemp); ///参数是路径 (完整)

%>
<script>
alert("图片上传成功!");
</script>
<%
}
}catch (Exception e){
System.out.println(e.getMessage());
%>
<script type="text/javascript">
alert("图片上传失败!");
</script>
<%
}
%>


</script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>首页</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="dscription" content="This is my page">
</head>
<body>
<form action="ImageUpload.jsp" method="post" enctype="multipart/form-data">
<table>
<tr>
<td width="120" align="center">路径:</td>
<td width="180"><input type="file" name="file" class="from_len21" contenteditable="false"></td>
</tr>
<tr>
<td>
<input type="submit" value="确定" />
</td>
</tr>
</table>
</form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值