資源簡介
基于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;
}
}
- 上一篇:ultimate-member
- 下一篇:廣東工業大學數字信號處理實驗報告
評論
共有 條評論