jsp表单中包含图片上传方法

2013/3/8 13:58:9 | 阅13023 来源:好空间网络 [打印] [关闭]
 

要求: 允许用户在填写表单的时候上传一个或者多个图片,图片上传到服务器后按照上传日期存放于不同的文件夹里!避免使用一个文件夹,里面图片过多的问题,大家可以根据这个例子举一反三增加更多的功能!!


准备工作: 此程序需要个 jspsmartupload.jar jar文件,右键另存为即可,下载后把他上传到工程下的lib文件夹里


第一步先给用户一个htm网页,用于选择上传图片用(upload.htm)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>

<body>
<form action="smartupload.jsp" method="post" enctype="multipart/form-data">
文件标题:<input type="text" name="uname"><br>
图片:<input type="file" name="pic"><br>
<input type="submit" value="上传">
</form>
</body>
</html>



我直接上用于上传的jsp文件,,jsp文件里面我已经写了很详细的注释了


smartupload.jsp内容:


<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.io.*" %>
<jsp:useBean id="smartupload" class="com.jspsmart.upload.SmartUpload"/>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>


<title>My JSP 'smartupload04.jsp' starting page</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="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
<%
request.setCharacterEncoding("GBK") ;
smartupload.initialize(pageContext) ; // 初始化上传
smartupload.upload() ; // 准备上传

String name = smartupload.getRequest().getParameter("uname") ; //这个是获取备注
java.text.SimpleDateFormat formatter2=new java.text.SimpleDateFormat("yyyy-MM-dd");
java.util.Date Now2=new java.util.Date();
String time2=formatter2.format(Now2);
//上面是建立日期的文件夹
//下面是记录卡时间的文件名称
java.text.SimpleDateFormat formatter=new java.text.SimpleDateFormat("hh-mm-ss");
java.util.Date Now=new java.util.Date();
String time=formatter.format(Now);
String name2 = time + "." + smartupload.getFiles().getFile(0).getFileExt() ; //这个是用备注的名称做文件的名称

//下面是判断文件夹是否存在,不存在就建立他
String Save_location="";
String Save_package="";
Save_package=time2;//以日期作为为文件夹名
Save_package=Save_package.trim(); //去除空格

Save_location="d:/www.jspkongjian.net/upload/"+Save_package; //文件夹的具体路径

File ml = new File(Save_location);
if(ml.exists())
{}else{
ml.mkdir();
}

//以上是判断文件夹是否存在,不存在则建立他
//以下是负责具体的上传工作
String fileName = Save_location+"/"+name2 ;
smartupload.getFiles().getFile(0).saveAs(fileName) ;

%>

<img src="upload/<%=time2%>/<%=name2%>" width="300" height="200">
</body>
</html>



在跟目录下建立upload 文件夹,上传一个图片后他会自动判断文件夹是否存在自动建立对应的日期文件夹,,图片名称为时间.jpg 这样不会有2个文件名称相同的问题!!!

经营许可证ICP:皖B2-20100052 公司邮箱:zcdnsz@jspkongjian.net
Copyright © 2004-2015, 安徽好空间网络科技有限公司 版权所有 , 本站素材部分来源于网络,如有侵权请告知删除。