struts 文件上传

         String textname="";//原文件名
String newpath1="";//下载后文件名
//上传文件
if(pForm.getFile()!=null){
int filesize =  pForm.getFile().getFileSize();
if (filesize>5*1024*1024){
request.setAttribute("msg", "file is too bigger!it must be less then 5M");
return mapping.getInputForward();
}




String path = "/upload";
String realPath = this.servlet.getServletContext().getRealPath(path);

File file = new File(realPath);
if (!file.exists()){
file.mkdirs();
}

try {
String newfilename = String.valueOf(System.currentTimeMillis());
String extendsname = pForm.getFile().getFileName().substring(pForm.getFile().getFileName().lastIndexOf(".")+1) ;

textname=pForm.getFile().getFileName().substring(pForm.getFile().getFileName().lastIndexOf("/")+1);
System.out.println(textname+"==========textname");
String newpath = realPath + "/" +newfilename+"."+extendsname;
newpath1 = newfilename+"."+extendsname;
InputStream is = pForm.getFile().getInputStream();
FileOutputStream fos = new FileOutputStream(newpath);

byte[]b = new byte[2048];
int len = 0;
while((len = is.read(b, 0, 2048))!=-1){
fos.write(b, 0, len);
}
fos.flush();
fos.close();
is.close();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

你可能感兴趣的:(struts,servlet)