读书人

JSP中的上传有关问题

发布时间: 2012-04-12 15:46:35 作者: rapoo

JSP中的上传问题
在用户注册界面,要上传一个用户的头像,那么怎么才能做到这个上传后的路径和这个用户绑定呢?

[解决办法]
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
//ActionMessages mess=new ActionMessages();

String dir=servlet.getServletContext().getRealPath( "/upload ");
File scfile=new File(dir);
if(!scfile.exists()){
scfile.mkdir();
}
HtmlFileForm hff=(HtmlFileForm)form;
FormFile file=hff.getFile();
String flname=file.getFileName();
if(flname==null||flname.equals( " ")){
this.setFileErrorMessage( "sssss ");
request.setAttribute( "error1 ", this.fileErrorMessage);
return mapping.findForward( "failure ");
}

//ナミカマホトシ�タヘ
int imgType=flname.lastIndexOf( ". ");
String imgTypeStr=flname.substring(imgType);

//スォホトシ�テ逸ヲタ昕ノオアフ�ネユニレ+ヒエハ�
String date=DNSUtility.getCurrentYeanMonthDay();
String[] dateStr=date.split( "/ ");
String dateName=dateStr[0]+dateStr[1]+dateStr[2];

Random random = new Random();
int rdInt=random.nextInt(1000000000);
String rdStr=String.valueOf(rdInt);

String fname=dateName+rdStr+imgTypeStr;
//ア」エスハ�センソ�

String urlTemp= "./upload/ ";
String picUrl=urlTemp+fname;
//ナミカマホトシ�エ。
if(file.getFileSize()> 2097152){
this.setSizeErrorMessage( "カヤイサニャヌ�イヤトマエォオトヘシニャハヌキ�ネキ(ホトシ�メムセュウャケ�2M)! ");
request.setAttribute( "error2 ", this.sizeErrorMessage);
return mapping.findForward( "failure ");
}
//ナミカマホトシ�タヘ
//ア」エ�.swfホトシ�オスflashア�

if(imgTypeStr.equals( ".swf ")){
String size=Integer.toString(file.getFileSize())+ "bytes ";
InputStream streamIn=file.getInputStream();
OutputStream streamOut=new FileOutputStream(dir+ "/ "+fname);
int bytesRead=0;
byte[] buffer=new byte[8192];
while((bytesRead=streamIn.read(buffer,0,8192))!=-1){
streamOut.write(buffer, 0, bytesRead);
}
streamOut.close();
streamIn.close();
hff.setFname(fname);
hff.setSize(size);
file.destroy();
this.pictureComponentsService.insertFlashUrl(picUrl);
return mapping.findForward( "success ");
}
if(!imgTypeStr.equals( ".jpg ")&&!imgTypeStr.equals( ".gif ")&&!imgTypeStr.equals( ".jpeg ")&&!imgTypeStr.equals( ".png ")&&!imgTypeStr.equals( ".swf ")){


this.setTypeErrorMessage( "カヤイサニャヌ�イヤトマエォオトヘシニャタヘ! ");
request.setAttribute( "error3 ",this.typeErrorMessage);
return mapping.findForward( "failure ");
}

String size=Integer.toString(file.getFileSize())+ "bytes ";
InputStream streamIn=file.getInputStream();
OutputStream streamOut=new FileOutputStream(dir+ "/ "+fname);
int bytesRead=0;
byte[] buffer=new byte[8192];
while((bytesRead=streamIn.read(buffer,0,8192))!=-1){
streamOut.write(buffer, 0, bytesRead);
}
streamOut.close();
streamIn.close();
hff.setFname(fname);
hff.setSize(size);
file.destroy();
this.pictureComponentsService.insertPicUrl(picUrl);
return mapping.findForward( "success ");

}

读书人网 >Java Web开发

热点推荐