67,513
社区成员
发帖
与我相关
我的任务
分享
@Controller
@Namespace("/")
@ParentPackage(value = "struts-default")
@Results(@Result(name = "fail", location = "/failed.jsp"))
//@InterceptorRefs( { @InterceptorRef(value = "fileUploadStack"),@InterceptorRef(value="defaultStack")})
public class UserPhotoAction extends BaseAction {
private static final long serialVersionUID = 6660814006888145788L;
// 用户相册管理Service
@Resource(name = "userPhotoServiceImpl")
private UserPhotoService userPhotoService;
//指定上传时的缓存大小为1MB
private static final int BUFFER_SIZE = 1 * 1024 * 1024;
//上传的文件和表单域的name一致
private File myFile;
//上传文件的MIME类型
private String contentType;
//上传文件的文件名,该文件名不包括文件的路径
private String fileName;
private String msg;
private Photo po;
public Photo getPo() {
return po;
}
public void setPo(Photo po) {
this.po = po;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public void setMyFileContentType(String contentType) {
this.contentType = contentType;
}
public void setMyFileFileName(String fileName) {
System.out.println("fileName>>>>>>>>>>>>>>>>" + fileName);
this.fileName = fileName;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
/**
* 上传文件时IO流操作(上传时所需函数1)
* @param src 表单域接收的源文件
* @param dst 上传的文件保存地址
*
* */
private static boolean copy(File src, File dst) {
try {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src),
BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
while (in.read(buffer) > 0) {
out.write(buffer);
}
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("文件保存时发生错误>>>>>>>"+e.getMessage());
return false;
}
return true;
}
/**
* 获取上传文件的扩展名(上传时所需函数2)
* @param fileName 上传文件的文件名,该文件名不包括文件的路径
* @return 扩展名(String)
* */
private static String getExtention(String fileName) {
System.out.println("fileName>>>>>>>>>>>>>>>>" + fileName);
int pos = fileName.lastIndexOf(".");
return fileName.substring(pos);
}
@SuppressWarnings("static-access")
@Action(value = "/upload", results = { @Result(name = SUCCESS, location = "/success.jsp") }, interceptorRefs = { @InterceptorRef("fileUploadStack") })
public String upload()throws Exception{
//由系统时间生成的文件名,数据库保存的文件名
String imageFileName = new Date().getTime() + getExtention(fileName);
//File imageFile = new File(ServletActionContext.getServletContext().getRealPath("/UploadImages") + "/" + imageFileName);
File imageFile = new File(this._resourcePath + "/user/" + imageFileName);
if(copy(myFile, imageFile)){
Photo p=new Photo();
p.setPhotoName(imageFileName);
p.setAddTime(UtilTools.getDate());
p.setDescribes(po.getDescribes());
p.setUploaderId(1);
userPhotoService.addPhoto(p);
msg="上传成功!";
return SUCCESS;
}else{
msg="上传失败!";
return "fail";
}
}
}