基于struts上传头像功能


基于struts上传头像功能,采用showModalDialog进行窗口弹出上传,关闭窗口实时更新头像,有需要的请猛击下载
资源截图
代码片段和文件信息
package net.blogjava.upload;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

public class UploadImageAction extends Action {

@Override
public ActionForward execute(ActionMapping mapping ActionForm form
HttpServletRequest request HttpServletResponse response)
throws Exception {
UploadImageForm uploadForm = (UploadImageForm) form;
FormFile image = uploadForm.getFormFile();
if (image.getFileSize() == 0) {
request.setAttribute(“msg“ “你还没选择文件呢!“);
return mapping.findForward(“input“);
}
if (!checkImageContentType(image)) {
request.setAttribute(“msg“ “图片类型不正确,请重新选择!“);
return mapping.findForward(“input“);
}
String path = servlet.getServletContext().getRealPath(“/upload/image“);
path += “/“;
String photoName = “superxzl“;
photoName = photoName
+ image.getFileName().substring(
image.getFileName().lastIndexOf(“.“));
System.out.println(“[PhotoName]“ + photoName);
File file = new File(path);
if (!file.exists()) {
file.mkdir();
}
try {
InputStream stream = image.getInputStream();
OutputStream bos = new FileOutputStream(path + photoName);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer 0 8192)) != -1) {
bos.write(buffer 0 bytesRead);
}
bos.close();
stream.close();
} catch (FileNotFoundException fnfe) {
request.setAttribute(“msg“ “文件路径不正确,请重新选择!“);
return mapping.findForward(“input“);
} catch (IOException ioe) {
request.setAttribute(“msg“ “上传出错,请重来!“);
return mapping.findForward(“input“);
}

image.destroy();
System.out.println(“[Photo_Src]“
+ servlet.getServletContext().getContextPath() + “/image/“
+ image.getFileName());
// String photoPath =
// servlet.getServletContext().getContextPath()+“/image/“ +
// image.getFileName();
request.setAttribute(“fileName“ photoName);
request.setAttribute(“msg“ “success“);
return mapping.findForward(“input“);
}

private boolean checkImageContentType(FormFile formFile) {
String contentType = formFile.getContentType();
System.out.println(“[ContentType]“ + contentType);
if (contentType.equals(“image/pjpeg“)
|| contentType.equals(“image/jpeg“)
|| contentType.equals(“image/gif“)
|| contentType.equals(“image/bmp“)) {
return true;
}
return false;
}

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件举报,一经查实,本站将立刻删除。

发表评论

评论列表(条)