码迷,mamicode.com
首页 > Web开发 > 详细

Struts1.x上传

时间:2015-08-05 21:59:48      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

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");
}
}

Struts1.x上传

标签:

原文地址:http://www.cnblogs.com/lbblog/p/4705827.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!