81,091
社区成员
发帖
与我相关
我的任务
分享
package com.action;
import com.action.Dao;
import com.opensymphony.xwork2.ActionSupport;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import org.apache.struts2.ServletActionContext;
public class upload extends ActionSupport{
private String username;
private File photo;
private String photoContentType;
private String photoFileName;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public File getPhoto() {
return photo;
}
public void setPhoto(File photo) {
this.photo = photo;
}
public String getPhotoContentType() {
return photoContentType;
}
public void setPhotoContentType(String photoContentType) {
this.photoContentType = photoContentType;
}
public String getPhotoFileName() {
return photoFileName;
}
public void setPhotoFileName(String photoFileName) {
this.photoFileName = photoFileName;
}
public String execute() throws Exception{
System.out.println("名字:"+getPhotoFileName());
if(getPhotoFileName()!=null && isEnableUploadType(1,getPhotoFileName())){
String filename=ServletActionContext.getRequest().getRealPath("/images").replaceAll("\\\\", "/") +"/"+getPhotoFileName();
/*String filename=ServletActionContext.getServletContext().getRealPath("/images");*/
System.out.println(filename);
FileOutputStream fos = new FileOutputStream(filename);
FileInputStream fis =new FileInputStream(getPhoto());
/* byte[] buf =new byte[1024];
int len=0;
while((len=fis.read(buf))>0){
fos.write(buf,0,len);
}*/
String pic="images/"+getPhotoFileName();
Dao dao =new Dao();
String sql = "insert into admin(name,pic) values('"+getUsername()+"','"+pic+"')";
System.out.println("数据:"+sql);
dao.executeUpdate(sql);
if(fis!=null)fis.close();
if(fos!=null)fos.close();
}else{
addFieldError("photo", "对不起,图片类型不正确!");
return INPUT;
}
return SUCCESS;
}
private static boolean isEnableUploadType(int filetype, String filename) {
// TODO Auto-generated method stub
String enableExtName=null;
int p=filename.lastIndexOf(".");
String fileExtName=filename.substring(p).toLowerCase();
if(filetype==1){//图片类型
enableExtName=".jpg,.gif,.png,.bmp";
}else if(filetype==2){
enableExtName=".flv,.mpg,.wmv,.rm";
}
if(enableExtName!=null){
if(enableExtName.indexOf(fileExtName)!=-1)return true;
else return false;
}else{
return true;
}
}
}