日期:2014-05-18  浏览次数:20689 次

jsp上传文件是不是都在用别人编写好的代码,有自己来编写的吗?
我想知道,jsp上传的服务器中的原理。

------解决方案--------------------
-----------------------------7d62ae1e1c0126
Content-Disposition: form-data; name= "textfield2 "; filename= "H:\图2.jpg "
Content-Type: image/pjpeg

 JFIF  ` `  C  

 $. ' ",#(7),01444 '9=82 <.342 C 

2!!22222222222222222222222222222222222222222222222222  ?@ "   
-----------------------------7d62ae1e1c0126
Content-Disposition: form-data; name= "textfield "


-----------------------------7d62ae1e1c0126
Content-Disposition: form-data; name= "Submit "

提交
-----------------------------7d62ae1e1c0126--
这是文件上传的接收格式,希望对你有帮助
------解决方案--------------------
UP
------解决方案--------------------
看看代码,自己研究一下吧,挺简单


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( "请选择你要上传的图片 ");
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 ");
}
//判断文件类型
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.insertPi