/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package accp.struts.action;
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.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.upload.FormFile;
import accp.struts.form.HtmlFileForm;
public class HtmlFileAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
HtmlFileForm hff = (HtmlFileForm) form;// TODO Auto-generated method stub
FormFile file=hff.getFile();
String fname="";
if(file.getFileSize()>0)
{
fname=file.getFileName();
int beginIndex=fname.indexOf(".");
String fileType=fname.substring(beginIndex);
if(fileType.equals(".jpg") || fileType.equals(".gif"))
{
try{
String savePath="E:\\SSH\\tagDemo2\\WebRoot\\upload";
InputStream streamIn=file.getInputStream();//从文件中读取流写入内存中
OutputStream streamOut=new FileOutputStream(savePath+"/"+fname);//把文件保存到制定路径
int bytesRead=0;
byte[] buffer=new byte[8192];
bytesRead=streamIn.read(buffer,0,8192);
while(bytesRead!=-1){//当读到最后一个字节的时候就不在写入硬盘了!也就跳出了循环
streamOut.write(buffer,0,bytesRead);//写入硬盘
bytesRead=streamIn.read(buffer,0,8192);//从内存中读取
}
streamOut.close();
streamIn.close();
}catch(IOException io){
io.printStackTrace();
}
String error="文件上传成功";
request.setAttribute("fname", fname);
request.setAttribute("fileError", error);
return mapping.findForward("showjpg");
}else
{
/*ActionErrors error=new ActionErrors();
ActionMessage message=new ActionMessage("文件类型不正确");
error.add("file",message);*/
String error="文件类型不对";
request.setAttribute("fileError", error);
return mapping.findForward("htmlFile");
}
}else
{
return mapping.findForward("htmlFile");
}
}
}