文件上传
1,在页面要注意写上 enctype="multipart/form-data"
<form action="fileup.do?method=simpleUpload" method="post" enctype="multipart/form-data">
姓名:<input type="text" name="username"/><br/>
文件:<input type="file" name="upFile" />
<input type="submit" value="提交"/>
</form>
2,在formBean中用formFile类型来接收,当然前提是要在<action>中配置name属性来指明formbean
==== form-bean
private String username;
private FormFile upFile ;
=====struts-config.xml
<action path="/fileup" type="hwt.action.SimpleFileUploadAction" parameter="method" name="fm">
</action>
3,为了防止文件名的乱码,可以使用一个过滤器,如果是整合了spring的话就是用spring的
======web.xml
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>hwt.filter.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<!-- 这里可以这样写,拦截servlet的名字为action里面的请求,其他的不处理 -->
<servlet-name>action</servlet-name>
</filter-mapping>
=======实现类,继承Filter
public class EncodingFilter implements Filter {
private String encoding;
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException {
this.encoding = config.getInitParameter("encoding");
}
}
4,action中的要注意的几点
public class SimpleFileUploadAction extends DispatchAction{
public ActionForward simpleUpload(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
response.setContentType("text/html;charset=utf-8");
FileForm fileForm = (FileForm)form;
//得到注册表单中的username
String username = fileForm.getUsername();
//得到文件上传的formFile
FormFile file = fileForm.getUpFile();
//得到文件上传的文件名
String fileName = file.getFileName();
//得到file的大小
int size = file.getFileSize();
//得到file的内容
//得到file的内容一般不是这样得到,这样得到的话如果文件很大的话,发在字节的数组中会是内存溢出
//不仅对于文件上传,对于其他的操作,很大的数据不能放在字节的数组中,一般用流来出来,通过流一点一点的来读
//byte[] b = file.getFileData();
//得到输入流,这里就相当于把管子的一头插入到客户端
InputStream is = file.getInputStream();
//得到服务器上的绝对路径
String path = this.getServlet().getServletContext().getRealPath("/");
//new出一个File
File upFile = new File(path,fileName);
//输出流,这里就相当于把管子插入服务器
OutputStream os = new FileOutputStream(upFile);
//输出到服务,这里就相对如开始在管子里面传输
int len = 0 ; //--实际读到的大小
byte[] b = new byte[1024]; //--想要读多少
while((len = is.read(b))!= -1){
os.write(b, 0, len);
}
os.close();
is.close();
response.getWriter().print("文件名:"+fileName+"<br/>文件大小:"+file.getFileSize());
return null;
}
}

被折叠的 条评论
为什么被折叠?



