标签:
1,jsp页面上传控件
<form action="/easyuiSSH/model/upload.do" enctype="multipart/form-data" method="post">
<input type="file" name="myfile"/>
<html:submit/><html:cancel/>
</form>
2,form定义上传文件类型
package com.platform_easyuiSSH.struts1.action.form;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
public class UploadForm extends ActionForm{
/**
* 序列号相当于类的身份证,如果你持久化操作,之后该类做了改动,在持久化会报错,而有了序列号,则会把持久化到硬盘的类一起改变
*/
private static final long serialVersionUID = 1L;
private FormFile myfile;
public FormFile getMyfile() {
return myfile;
}
public void setMyfile(FormFile myfile) {
this.myfile = myfile;
}
}
3,action执行上传操作
package com.platform_easyuiSSH.struts1.action;
import java.io.FileOutputStream;
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;
import com.platform_easyuiSSH.struts1.action.form.UploadForm;
public class UploadAction extends Action{
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
UploadForm uf = (UploadForm) form;
FormFile myfile = uf.getMyfile();
//文件名
String fileName = myfile.getFileName();
//文件大小
int fileSize = myfile.getFileSize();
//文件类型
String fileType = myfile.getContentType();
System.out.println("文件名:"+fileName+"\t文件大小:"+fileSize+"\t文件类型:"+fileType);
String realPath = request.getSession().getServletContext().getRealPath("/upload");
System.out.println(realPath);
if( fileSize != 0){
//输入流接收文件,字节数组太小不适合
InputStream is = myfile.getInputStream();
byte[] buf = new byte[1024];
OutputStream os = new FileOutputStream(realPath+"\\"+fileName);
while(true){
int len = is.read(buf);
if(len == -1){
break;
}
os.write(buf, 0, len);
}
os.close();
is.close();
}
return mapping.findForward("logoutSuccess");
}
}
标签:
原文地址:http://www.cnblogs.com/lbblog/p/4705827.html