package com.zhou.study ;
import java.text.SimpleDateFormat ;
import java.util.Date ;
import java.util.Random ;
public class IPTimeStamp {
private SimpleDateFormat sdf = null ;
private String ip = null ;
public IPTimeStamp(){
}
public IPTimeStamp(String ip){
this.ip = ip ;
}
public String getIPTimeRand(){
StringBuffer buf = new StringBuffer() ;
if(this.ip != null){
String s[] = this.ip.split("\\.") ;
for(int i=0;i<s.length;i++){
buf.append(this.addZero(s[i],3)) ;
}
}
buf.append(this.getTimeStamp()) ;
Random r = new Random() ;
for(int i=0;i<3;i++){
buf.append(r.nextInt(10)) ;
}
return buf.toString() ;
}
public String getDate(){
this.sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") ;
return this.sdf.format(new Date()) ;
}
public String getTimeStamp(){
this.sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS") ;
return this.sdf.format(new Date()) ;
}
private String addZero(String str,int len){
StringBuffer s = new StringBuffer() ;
s.append(str) ;
while(s.length() < len){
s.insert(0,"0") ;
}
return s.toString() ;
}
public static void main(String args[]){
System.out.println(new IPTimeStamp().getIPTimeRand()) ;
}
}
附上使用方法:
复制代码 代码如下:
<html>
<head><title>smartupload上传文件重命名</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head>
<body>
<form action="smartupload_demo03.jsp" method="post" enctype="multipart/form-data">
姓名<input type="text"><br>
照片<input type="file"><br>
<input type="submit" value="上传">
<input type="reset" value="重置">
</form>
</body>
</html>
Jsp代码:
smartupload_demo03.jsp
复制代码 代码如下:
<%@ page contentType="text/html" pageEncoding="utf-8"%>
<%@ page import="com.jspsmart.upload.*" %>
<%@ page import="com.zhou.study.*"%>
<html>
<head><title>smartupload</title></head>
<body>
<%
SmartUpload smart = new SmartUpload() ;
smart.initialize(pageContext) ; //初始化上传操作
smart.upload() ; // 上传准备
String name = smart.getRequest().getParameter("uname") ;
String str = new String(name.getBytes("gbk"), "utf-8"); //传值过程中出现乱码,在此转码
IPTimeStamp its = new IPTimeStamp("192.168.1.1") ; // 取得客户端的IP地址
String ext = smart.getFiles().getFile(0).getFileExt() ; // 扩展名称
String fileName = its.getIPTimeRand() + "." + ext ;
smart.getFiles().getFile(0).saveAs(this.getServletContext().getRealPath("https://www.jb51.net/")+"upload"+java.io.File.separator + fileName) ;
out.print("上传成功");
%>
<h2>姓名:<%=str%></h2>
<img src="https://www.jb51.net/upload/<%=fileName%>">
</body>
</html>