首 页 | 网页模板 | 教程 | 源码下载 | 书籍下载 | 图片素材 | 字体 | JAVA特效 | FLASH源码 | 软件 | 矢量 | 论坛 | 其它 |
设为主页
加入收藏
联系站长
平面设计 | 网页制作 | 程序编写 | 数 据 库 | 媒体动画 | 网络冲浪 | 服务器相关 |
当前在线
广告:P4服务器电信机房6999/年即送产权 | 疾风下载
初学jsp心得(三)
2005-3-18 5:56:40  作者:模板天下收集整理  来源:未知 网友评论 0 条 论坛
  第三部分:JavaMail和JSP的结合


创建JSP

下面我们将开始将他们结合在一起。最重要的一点是要确认根据页面指示分类。还要记得在邮件上标注java.util.date。


<%@ page

import= " javax.mail.*, javax.mail.internet.*, javax.activation.*, java.util.*"

%>

其次,创建邮件发送的确认信息。确认信息可以是任意的,一般常用"你的邮件已经发送出去了(Your mail has been sent)。"


信息是如何创建和发送的


我们在第二部分里已经讨论过信息对象的创建。我们下面将对信息进行操作。这就和设置信息对象的属性一样简单。你可以通过下面的程序来实现这项操作。


newMessage.setFrom(new InternetAddress(request.getParameter("from")));


newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(request.getParameter("to")));


newMessage.setSubject(request.getParameter("subject"));


newMessage.setSentDate(new Date());


newMessage.setText(request.getParameter("text"));


现在将开始发送信息。通过JavaMail来实现它非常简单。


transport.send(newMessage);


将所有的组件结合在一起


现在所有的组件都已经齐全了。现在将它们都放在JSP里面。要注意每一个错误信息,并将它反馈给用户。代码如下,你可以通过复制它们直接使用:


Sample JSP email Utility Using JavaMail

<%@ page

import=" javax.mail.*, javax.mail.internet.*, javax.activation.*,java.util.*"

%>





JSP meets JavaMail, what a sweet combo.





<%

try{

Properties props = new Properties();

Session sendMailSession;

Store store;

Transport transport;

sendMailSession = Session.getInstance(props, null);

props.put("mail.smtp.host", "smtp.jspinsider.com");

Message newMessage = new MimeMessage(sendMailSession);

newMessage.setFrom(new InternetAddress(request.getParameter("from")));

newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(request.getParameter("to")));

newMessage.setSubject(request.getParameter("subject"));

newMessage.setSentDate(new Date());

newMessage.setText(request.getParameter("text"));

transport = sendMailSession.getTransport("smtp");

transport.send(newMessage);

%>

Your mail has been sent.



<%

}

catch(MessagingException m)

{

out.println(m.toString());

}

%>





你会很快体会到JavaMail的方便之处,JSP和JavaMail将是未来的希望。



文件/图片上传
package uploadfile;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.*;
import java.util.Hashtable;
import java.util.*;

public class FileUploadBean {

private String savePath=null; //文件上传保存的路径
private String contentType=""; //内容类型
private String charEncode=null; //字符编码
private String bounary=""; //分界线
private String fileName=null; //本地文件名字
private Hashtable dic=new Hashtable(); //用于保存"元素名--元素值"对
private int totalSize=0; //上传文件总大小
private String path=""; //保存文件的路径
private String newFileName=""; //存入随机产生的文件名


///////////////////////////////////////////////////
//设置文件上传保存的路径
public void setSavePath(String s) {
s=path+s;
savePath=s;
System.out.println("上传路径:"+savePath);
}

///////////////////////////////////////////////////
//取文件上传保存的路径
public String getSavePath() {
return savePath;

}

////////////////////////////////////////////////////
//设置文件名字,也可以为它命名,暂时先用它原来的名字
public void setFileName(String s) {
int pos=s.indexOf("\"; filename=\"");
if (pos>0) {
s=s.substring(pos+13,s.length()-3); //去 " 和 crlf
pos=s.lastIndexOf("\\");
if (pos<0)
pos=s.lastIndexOf("/");
if (pos<0)
fileName=s;
fileName=s.substring(pos+1);
}
}

////////////////////////////////////////////////////
//取得文件名
public String getFileName() {
System.out.println("得到文件名"+newFileName);
return newFileName;

}
///////////////////////////
//以时间为种子数产生新文件名
public String getNewFileName() {
int pos=0; //.的位置
long seed=0; //随机种子数
String ext=""; //存入文件扩展名
System.out.println("upload file name:"+fileName);
pos=fileName.lastIndexOf(".");
ext=fileName.substring(pos); //得到扩展名
seed=new Date().getTime();
Random rand=new Random(seed);//以时间为种子产生随机数作为文件名
newFileName=Long.toString(Math.abs(rand.nextInt()))+ext; //生成文件名
System.out.println("new file name:"+newFileName);
return newFileName;

}
//////////////////////////////////////////////////////
//设置字符的编码方式
public void setCharEncode(HttpServletRequest req) {
charEncode=req.getCharacterEncoding();
}




/////////////////////////////////////////////////
//设置得ContentType
public void setBoundary(HttpServletRequest req) {
//传递的参数值类似"multipart/form-data; boundary=---------------------------7d21441a30013c"
//传过来的分界线比实际显示在上传数据中的要多两个"--"

boundary=req.getContentType();
//System.out.println("boundary"+boundary);
int pos=boundary.indexOf("boundary=");
//加上这两个"--"
boundary="--"+boundary.substring(pos+9);


}

////////////////////////////////////////////////////
//取得ContentType
public String getBoundary(){
//返回值类似"-----------------------------7d21441a30013c"
return boundary;
}


/////////////////////////////////////////////
//设置ContentType
public void setContentType(String s) {
int pos =s.indexOf(": ");
if (pos!=-1)
contentType=s.substring(pos+2);
}

////////////////////////////////////////////
//取得ContentType
public String getContentType() {
return contentType;
}

/////////////////////////////////////////////
//初始化
public void init(HttpServletRequest req) {
setCharEncode(req);
setBoundary(req);

}


////////////////////////////////////////////////////
//取哈希表中的数据
public String getFieldValue(String s) {
String temp="";
if(dic.containsKey(s)) //判断表中是否存在s键,不判断则返回nullpointerException
{
temp=(String)dic.get(s);
temp=temp.trim();
}else
temp="";
return temp;
}



////////////////////////////////////////////////
////用指定的编码方式生成字符串
public String newLine(byte oneLine[],int sp,int i,String charEncode)
throws java.io.UnsupportedEncodingException {
sp=0; // start position
String lineStr=null;
if (charEncode!=null) {
return lineStr=new String(oneLine,sp,i,charEncode); //用指定的编码方式生成字符串
}
else {
return lineStr=new String(oneLine,sp,i);
}
}

///////////////////////////////////////////////
//得到上传文件的大小
public int getTotalSize() {
return totalSize/1000;
}
///////////////////////////////////////
//删除指定路径的文件
public boolean delFiles(String fn) //fn为要删除的文件名,不包括路径
{
try
{
File file=new File(savePath+fn);
System.out.println(savePath+fn);
if(file.exists())
{
file.delete();
System.out.println(file.getPath()+"delete file successfully!");
return true;
}else
{
System.out.println("the file is not existed!");
return true;
}
}catch(Exception e)
{
System.out.println(e.toString());
return false;
}
}

////////////////////////////////////////////////
//文件列表
public String[] listFiles(String fp)
{
String[] lf=null;
try{
savePath=path+fp;
File file=new File(savePath);
lf=file.list(new DirFilter());
for(int i=0;iSystem.out.println(lf[i]);
}catch(Exception e){ e.printStackTrace();}
return lf;
}
/////////////////////////////////////////////////
//开始上传文件
public boolean doUpload(HttpServletRequest req)
throws java.io.IOException {

String fieldValue=""; //表单元素值
String fieldName=""; //表单元名称
int pos=-1; //临时变量,用于记录位置
int pos2=-1; //临时变量,用于记录位置
String lineStr=null; //用oneLine[]生成的每行字符串
byte oneLine[] =new byte[4096]; //用于每次读取的数据
FileOutputStream fos=null; //文件输出流
init(req); //初始化
ServletInputStream sis=req.getInputStream();
int i=sis.readLine(oneLine,0,oneLine.length); //返回实际读取的字符数,并把数据写到oneLine中
while (i!=-1) {
lineStr=newLine(oneLine,0,i,charEncode); //生成字符串
if (lineStr.indexOf(getBoundary()+"--")>=0)
break;

if (lineStr.startsWith("Content-Disposition: form-data; name=\"")) {
//分离数据,因为表单元素也一并上传,还有其它数据,对我们有用的只是
//文件的内容,表单元素及表单元素对应的值
if (lineStr.indexOf("\"; filename=\"")>=0) { //是文件输入域
//设置文件名
setFileName(lineStr);
if (!fileName.equals("")) { //如果文件名为空则跳过

//提取表单元素名称及表单元素对应的值
pos=lineStr.indexOf("name=\"");
pos2=lineStr.indexOf("\"; filename=\"");
//表单元素名字
fieldName=lineStr.substring(pos+6,pos2);
//表单元素值
fieldValue=lineStr.substring(pos2+13,lineStr.length()-3);
//加入哈希表中
dic.put(fieldName,fieldValue);
sis.readLine(oneLine,0,oneLine.length); //读取的数据类似"Content-Type: text/plain"
sis.readLine(oneLine,0,oneLine.length); //空行
//建立文件输出
fos=new FileOutputStream(new File(getSavePath(),getNewFileName()));
//开始读上传文件数据
i=sis.readLine(oneLine,0,oneLine.length);
while(i!=-1) {
totalSize=i+totalSize;
lineStr=newLine(oneLine,0,i,charEncode);
if (lineStr.indexOf(getBoundary())>=0)
break; //表明这个文件区的数据读取完毕
fos.write(oneLine,0,i);
i=sis.readLine(oneLine,0,oneLine.length);
}//end while
fos.close();
}//end if (!getFileName().equals(""))
}
else { //非文件输入域
pos=lineStr.indexOf("name=\"");
//表单元素名字
fieldName=lineStr.substring(pos+6,lineStr.length()-3);
//读空行
sis.readLine(oneLine,0,oneLine.length);
//这行含有元素值,如里元素值为空,则这行也是空行,也要读的
String temp="";
i=sis.readLine(oneLine,0,oneLine.length);
while(i!=-1)
{
temp=newLine(oneLine,0,i,charEncode);
if (temp.indexOf(getBoundary())>=0)
break;
fieldValue=fieldValue+temp;
i=sis.readLine(oneLine,0,oneLine.length);
}
//加入哈希表中
dic.put(fieldName,fieldValue);
fieldValue="";
}
}
i=sis.readLine(oneLine,0,oneLine.length);
}//end while

sis.close();

return true;
} //end doUpload


//////////////////////////
//清空Hashtable
public void clearDic() {
dic.clear();
if (dic.isEmpty()) {
System.out.println("empty");
}
else {
Sstem.out.println("not empty");
}

}
//////////////////////////////////
//测试用的主函数
public static void main(String args[])
{
String[] fileList=null;
try{
FileUploadBean fub=new FileUploadBean();
fileList=fub.listFiles("/avatars/");
for(int i=0;iSystem.out.println(fileList[i]);

}catch(Exception e){ e.printStackTrace();}
}

}


///////////////////////////////////
////文件目录过滤内部类
class DirFilter implements FilenameFilter {

public boolean accept(File dir, String name) { //dir为目录名,name 为包含路径的文件名

File f = new File(dir,name); //生成文件对象
if(f.isDirectory())
return false;
return true;
}
}
相关类说明篇

㈠ File类

  这个类包装了一个上传文件的所有信息。通过它,可以得到上传文件的文件名、文件大小、扩展名、文件数据等信息。

  File类主要提供以下方法:

1、saveAs作用:将文件换名另存。

原型:

public void saveAs(java.lang.String destFilePathName)



public void saveAs(java.lang.String destFilePathName, int optionSaveAs)

其中,destFilePathName是另存的文件名,optionSaveAs是另存的选项,该选项有三个值,分别是SAVEAS_PHYSICAL,SAVEAS_VIRTUAL,SAVEAS_AUTO。SAVEAS_PHYSICAL表明以操作系统的根目录为文件根目录另存文件,SAVEAS_VIRTUAL表明以Web应用程序的根目录为文件根目录另存文件,SAVEAS_AUTO则表示让组件决定,当Web应用程序的根目录存在另存文件的目录时,它会选择SAVEAS_VIRTUAL,否则会选择SAVEAS_PHYSICAL。

例如,saveAs("/upload/sample.zip",SAVEAS_PHYSICAL)执行后若Web服务器安装在C盘,则另存的文件名实际是c:\upload\sample.zip。而saveAs("/upload/sample.zip",SAVEAS_VIRTUAL)执行后若Web应用程序的根目录是webapps/jspsmartupload,则另存的文件名实际是webapps/jspsmartupload/upload/sample.zip。saveAs("/upload/sample.zip",SAVEAS_AUTO)执行时若Web应用程序根目录下存在upload目录,则其效果同saveAs("/upload/sample.zip",SAVEAS_VIRTUAL),否则同saveAs("/upload/sample.zip",SAVEAS_PHYSICAL)。

建议:对于Web程序的开发来说,最好使用SAVEAS_VIRTUAL,以便移植。

2、isMissing

作用:这个方法用于判断用户是否选择了文件,也即对应的表单项是否有值。选择了文件时,它返回false。未选文件时,它返回true。

原型:public boolean isMissing()

3、getFieldName

作用:取HTML表单中对应于此上传文件的表单项的名字。

原型:public String getFieldName()

4、getFileName

作用:取文件名(不含目录信息)

原型:public String getFileName()

5、getFilePathName

作用:取文件全名(带目录)

原型:public String getFilePathName

6、getFileExt

作用:取文件扩展名(后缀)

原型:public String getFileExt()

7、getSize

作用:取文件长度(以字节计)

原型:public int getSize()

8、getBinaryData

作用:取文件数据中指定位移处的一个字节,用于检测文件等处理。

原型:public byte getBinaryData(int index)。其中,index表示位移,其值在0到getSize()-1之间。

㈡ Files类

  这个类表示所有上传文件的集合,通过它可以得到上传文件的数目、大小等信息。有以下方法:

1、getCount

作用:取得上传文件的数目。

原型:public int getCount()

2、getFile

作用:取得指定位移处的文件对象File(这是com.jspsmart.upload.File,不是java.io.File,注意区分)。

原型:public File getFile(int index)。其中,index为指定位移,其值在0到getCount()-1之间。

3、getSize

作用:取得上传文件的总长度,可用于限制一次性上传的数据量大小。

原型:public long getSize()

4、getCollection

作用:将所有上传文件对象以Collection的形式返回,以便其它应用程序引用,浏览上传文件信息。

原型:public Collection getCollection()

5、getEnumeration

作用:将所有上传文件对象以Enumeration(枚举)的形式返回,以便其它应用程序浏览上传文件信息。

原型:public Enumeration getEnumeration()

㈢ Request类

  这个类的功能等同于JSP内置的对象request。只所以提供这个类,是因为对于文件上传表单,通过request对象无法获得表单项的值,必须通过jspSmartUpload组件提供的Request对象来获取。该类提供如下方法:

1、getParameter

作用:获取指定参数之值。当参数不存在时,返回值为null。

原型:public String getParameter(String name)。其中,name为参数的名字。

2、getParameterValues

作用:当一个参数可以有多个值时,用此方法来取其值。它返回的是一个字符串数组。当参数不存在时,返回值为null。

原型:public String[] getParameterValues(String name)。其中,name为参数的名字。

3、getParameterNames

作用:取得Request对象中所有参数的名字,用于遍历所有参数。它返回的是一个枚举型的对象。

原型:public Enumeration getParameterNames()


㈣ SmartUpload类这个类完成上传下载工作。

A.上传与下载共用的方法:

只有一个:initialize。

作用:执行上传下载的初始化工作,必须第一个执行。

原型:有多个,主要使用下面这个:

public final void initialize(javax.servlet.jsp.PageContext pageContext)

其中,pageContext为JSP页面内置对象(页面上下文)。

B.上传文件使用的方法:

1、upload

作用:上传文件数据。对于上传操作,第一步执行initialize方法,第二步就要执行这个方法。

原型:public void upload()

2、save

作用:将全部上传文件保存到指定目录下,并返回保存的文件个数。

原型:public int save(String destPathName)

和public int save(String destPathName,int option)

其中,destPathName为文件保存目录,option为保存选项,它有三个值,分别是SAVE_PHYSICAL,SAVE_VIRTUAL和SAVE_AUTO。(同File类的saveAs方法的选项之值类似)SAVE_PHYSICAL指示组件将文件保存到以操作系统根目录为文件根目录的目录下,SAVE_VIRTUAL指示组件将文件保存到以Web应用程序根目录为文件根目录的目录下,而SAVE_AUTO则表示由组件自动选择。

注:save(destPathName)作用等同于save(destPathName,SAVE_AUTO)。

3、getSize

作用:取上传文件数据的总长度

原型:public int getSize()

4、getFiles

作用:取全部上传文件,以Files对象形式返回,可以利用Files类的操作方法来获得上传文件的数目等信息。

原型:public Files getFiles()

5、getRequest

作用:取得Request对象,以便由此对象获得上传表单参数之值。

原型:public Request getRequest()

6、setAllowedFilesList

作用:设定允许上传带有指定扩展名的文件,当上传过程中有文件名不允许时,组件将抛出异常。

原型:public void setAllowedFilesList(String allowedFilesList)

其中,allowedFilesList为允许上传的文件扩展名列表,各个扩展名之间以逗号分隔。如果想允许上传那些没有扩展名的文件,可以用两个逗号表示。例如:setAllowedFilesList("doc,txt,,")将允许上传带doc和txt扩展名的文件以及没有扩展名的文件。

7、setDeniedFilesList

作用:用于限制上传那些带有指定扩展名的文件。若有文件扩展名被限制,则上传时组件将抛出异常。

原型:public void setDeniedFilesList(String deniedFilesList)

其中,deniedFilesList为禁止上传的文件扩展名列表,各个扩展名之间以逗号分隔。如果想禁止上传那些没有扩展名的文件,可以用两个逗号来表示。例如:setDeniedFilesList("exe,bat,,")将禁止上传带exe和bat扩展名的文件以及没有扩展名的文件。

8、setMaxFileSize

作用:设定每个文件允许上传的最大长度。

原型:public void setMaxFileSize(long maxFileSize)

其中,maxFileSize为为每个文件允许上传的最大长度,当文件超出此长度时,将不被上传。

9、setTotalMaxFileSize

作用:设定允许上传的文件的总长度,用于限制一次性上传的数据量大小。

原型:public void setTotalMaxFileSize(long totalMaxFileSize)

其中,totalMaxFileSize为允许上传的文件的总长度。


jsp 上传图片并生成缩位图或者加水印
有些网站  动网, 上传图片后加给加上自己的字(是在图片上加的)

 请问在JSP里如何实现??
//添加水印,filePath 源图片路径, watermark 水印图片路径
public static boolean createMark(String filePath,String watermark) {
ImageIcon imgIcon=new ImageIcon(filePath);
Image theImg =imgIcon.getImage();
ImageIcon waterIcon=new ImageIcon(watermark);
Image waterImg =waterIcon.getImage();
int width=theImg.getWidth(null);
int height= theImg.getHeight(null);
BufferedImage bimage = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
Graphics2D g=bimage.creatGraphics( );
g.setColor(Color.red);
g.setBackground(Color.white);
g.drawImage(theImg, 0, 0, null );
g.drawImage(waterImg, 100, 100, null );
g.drawString("12233",10,10); //添加文字
g.dispose();
try{
FileOutputStream out=new FileOutputStream(filePath);
JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
param.setQuality(50f, true);
encoder.encode(bimage, param);
out.close();
}catch(Exception e){ return false; }
return true;
}

/////////////////范例////////////////////
package package;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

public class upload
{

private static String newline = "\n";
private String uploadDirectory;
private String ContentType;
private String CharacterEncoding;

public upload()
{
uploadDirectory = ".";
ContentType = "";
CharacterEncoding = "";
}

private String getFileName(String s)
{
int i = s.lastIndexOf("\\");
if(i < 0 || i >= s.length() - 1)
{
i = s.lastIndexOf("/");
if(i < 0 || i >= s.length() - 1)
return s;
}
return s.substring(i + 1);
}

public void setUploadDirectory(String s)
{
uploadDirectory = s;
}

public void setContentType(String s)
{
ContentType = s;
int i;
if((i = ContentType.indexOf("boundary=")) != -1)
{
ContentType = ContentType.substring(i + 9);
ContentType = "--" + ContentType;
}
}

public void setCharacterEncoding(String s)
{
CharacterEncoding = s;
}

public String uploadFile(HttpServletRequest httpservletrequest)
throws ServletException, IOException
{
String s = null;
setCharacterEncoding(httpservletrequest.getCharacterEncoding());
setContentType(httpservletrequest.getContentType());
s = uploadFile(httpservletrequest.getInputStream());
return s;
}

public String uploadFile(ServletInputStream servletinputstream)
throws ServletException, IOException
{
String s = null;
String s1 = null;
byte abyte0[] = new byte[4096];
byte abyte1[] = new byte[4096];
int ai[] = new int[1];
int ai1[] = new int[1];
String s2;
while((s2 = readLine(abyte0, ai, servletinputstream, CharacterEncoding)) != null)
{
int i = s2.indexOf("filename=");
if(i >= 0)
{
s2 = s2.substring(i + 10);
if((i = s2.indexOf("\"")) > 0)
s2 = s2.substring(0, i);
break;
}
}
s1 = s2;
if(s1 != null && !s1.equals("\""))
{
s1 = getFileName(s1);
String s3 = readLine(abyte0, ai, servletinputstream, CharacterEncoding);
if(s3.indexOf("Content-Type") >= 0)
readLine(abyte0, ai, servletinputstream, CharacterEncoding);
File file = new File(uploadDirectory, s1);
FileOutputStream fileoutputstream = new FileOutputStream(file);
while((s3 = readLine(abyte0, ai, servletinputstream, CharacterEncoding)) != null)
{
if(s3.indexOf(ContentType) == 0 && abyte0[0] == 45)
break;
if(s != null)
{
fileoutputstream.write(abyte1, 0, ai1[0]);
fileoutputstream.flush();
}
s = readLine(abyte1, ai1, servletinputstream, CharacterEncoding);
if(s == null || s.indexOf(ContentType) == 0 && abyte1[0] == 45)
break;
fileoutputstream.write(abyte0, 0, ai[0]);
fileoutputstream.flush();
}
byte byte0;
if(newline.length() == 1)
byte0 = 2;
else
byte0 = 1;
if(s != null && abyte1[0] != 45 && ai1[0] > newline.length() * byte0)
fileoutputstream.write(abyte1, 0, ai1[0] - newline.length() * byte0);
if(s3 != null && abyte0[0] != 45 && ai[0] > newline.length() * byte0)
fileoutputstream.write(abyte0, 0, ai[0] - newline.length() * byte0);
fileoutputstream.close();
}
return s1;
}

private String readLine(byte abyte0[], int ai[], ServletInputStream servletinputstream, String s)
{
ai[0] = servletinputstream.readLine(abyte0, 0, abyte0.length);
if(ai[0] == -1)
return null;
break MISSING_BLOCK_LABEL_27;
Object obj;
obj;
return null;
if(s == null)
return new String(abyte0, 0, ai[0]);
return new String(abyte0, 0, ai[0], s);
obj;
return null;
}

}


JSP页:

<%@page contentType="text/html;charset=gb2312" import="package.upload"%>
<%
String Dir = "c:\dir\upload";
String fn="";
upload upload = new upload();
upload.setUploadDirectory(Dir);
fn=upload.uploadFile(request);
%>

随机图片名称
<%
mySmartUpload.initialize(pageContext);
mySmartUpload.service(request,response);
mySmartUpload.upload();
String fn=mySmartUpload.getFiles().getFile(0).getFileName();
mySmartUpload.save("upload/"); //文件保存的目录为upload
out.println("已经成功上传了文件,请查看这里");
%>
上面的程序可以上传图片,不过只能上传gif或者JPG图片。
而且保存图片在upload文件夹下面,要想GIF或Jpg图片的名称变为年+月+日+随机数.gif或年+月+日+随机数.jpg
只允许上传jpg或gif图片,在客户端用javaScript控制要好些。
变图片名称可用如下代码:自己看看就明白了。:
//得到实际路径

String realPath = this.masRequest.getRequest().getRealPath("/");
String userPhotoPath = realPath + "images\\UserPhoto\\";
userPhotoPath = MasString.replace(userPhotoPath,"\\","\\\\");
if (!file.getFileName().trim().equals(""))
{
//根据系统时间生成文件名
Date nowTime = new Date();
emp_Photo = userPhotoPath + String.valueOf(nowTime.getTime()) +"."+ file.getFileExt();
file.saveAs(emp_Photo);
System.out.println("file.saveAs() = " + "OK!!!");
}
共分1页  [1] 
>> 相关文章

关于网站 | 客服中心 | 服务条款 | 友情链接 | 广告联系 | 本站历程 | 网站导航

吉ICP备05000107号