form 总有文件上传时 在form标签中 加入属性

enctype="multipart/form-data"   

 

  文件上传

private File logo_path;//机构有效身份证明文件
private String logo_pathContentType;// 上传文件类型
private String logo_pathFileName;// 上传头像文件名称
private static String Upd = StringConverter.getDateTimeToString(new Date()).substring(0,8);
public String shenFenupload(){
try {
//验证信息有效性
if(this.verifyJpg(logo_pathFileName,logo_path).equals("xk")){
return "xx";
}
if(this.verifyJpg(logo_pathFileName,logo_path).equals("xx")){
//保存文件
String srcurl=saveFile(logo_path,"company_logo",logo_pathFileName);
if(srcurl!=null){
return "xx";
}
}else{
return this.verifyJpg(logo_pathFileName,logo_path);
}
} catch (Exception e) {
e.printStackTrace();
}

return "cuow";
}
public String verifyJpg(String getname,File file){
// 验证上传文件

if (file != null&&getname!=null) {

if (!ProjectUtils.isJpgTypeAllowed(this.getExt(getname))) {
//文件类型不正确
return "公司图标文件类型不正确";
} else {
if (file.length() > (1024 * 300))
return "公司图标文件大小为300k";
}
}else if(file==null){
//没有上传文件
return "xk";
}
return "xx";
}
public String getExt(String filename) {
String ext="";
if (filename!=null){
ext = filename.substring(filename.lastIndexOf(".") + 1);
}
return ext;
}
// 保存申请书方法
public String saveFile(File file,String newname,String getname){
if (file!=null) {
String filename=newname+GenerateDistinctFileName(getname);
Properties prop = new Properties(System.getProperties());
String sep=prop.getProperty("file.separator");
String path = ServletActionContext.getServletContext().getRealPath(
Constant.FILE_PATCH)+sep+Upd;
if(saveFile(file, path, filename,newname,getname))
//this.realpath=path+"\\"+filename;
return filename;
}
return null;
}
public String GenerateDistinctFileName(String getname) {
String path = ServletActionContext.getServletContext().getRealPath(Constant.FILE_PATCH);
return ProjectUtils.generateDistinctFileName(path, this.getExt(getname));
}

public boolean saveFile(File file, String path, String filename,String newname,String getname) {
String str="";
try {
if (file != null) {
InputStream is = new FileInputStream(file);
File checkpath = new File(path);
//判断路径是否存在。如果不存在则创建
if (!checkpath.exists())
{
checkpath.mkdir();
}
String separator = File.separator;
str = path + separator + filename;
File outfile = new File(str);

OutputStream os = new FileOutputStream(outfile);
byte[] buffer = new byte[400];
int length = 0;
while ((length = is.read(buffer)) != -1) {
os.write(buffer, 0, length);
}
is.close();
os.close();
}
getSession().setAttribute(Constant.COMPANY_LOGO, str);  ///存入session  以便保存地址到数据库
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}

posted on 2013-04-09 14:49  远方的人  阅读(636)  评论(0编辑  收藏  举报

导航