struts上传文件的实现

jsp文件代码:

<%@ page language="java" pageEncoding="GB2312"%>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%> 
<html>
 <head>
  <title>HTML Tags</title>
 </head>
 <body>
  <html:form action="/upload" method="POST" enctype="multipart/form-data">

<html:file property="file"></html:file>

<html:submit/> <html:cancel/>

  </html:form>
 </body>
</html>

有以下几点需要注意:

1: <html:file>必须嵌套在<html:form>标签中。

2:<html:form>标签的method的属性必须设为"post".

3:<html:form>标签的编码类型enctype属性必须为"multipart/form-data"。

4:<html:file>标签必须设为property属性,这个属性和ActionForm Bean中FormFile类型的属性对应。

UploadForm.java文件部分代码:

private FormFile file;
public void reset(ActionMapping mapping, HttpServletRequest request) {
  this.file = null;
 }
public void setFile(FormFile file) {
  this.file = file;
 }

 public FormFile getFile() {
  return file;
 }

UploadAction.java文件部分代码:

public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) throws IOException {
  UploadForm uploadForm = (UploadForm) form;
   FormFile file = uploadForm.getFile();
  if(file != null){
   String strFileName = file.getFileName();  
   MessageResources mr = getResources(request);
   String strFilePath= mr.getMessage("FilePath");//获取资源文件中设置的路径
   try{
   InputStream is = file.getInputStream();
   OutputStream os = new FileOutputStream(strFilePath + "/" + strFileName);
   int byteRead = 0;
   byte[] buffer = new byte[8192];
   while((byteRead=is.read(buffer,0,8192)) != -1){
    os.write(buffer,0,byteRead);
   }
   os.close();
   is.close();
   file.destroy();
   }catch(Exception e){
    ...
   }

说明:在资源文件中设置了FilePath = D:/Program Files,在此把要上传的路径从资源文件中获取出来,如果要上传到系统当前运行的某个目录中的话可以通过以下方式来获取系统当前的路径:

request.getSession().getServletContext().getRealPath("/");

该方法同request.getRealPath("/")一样都可以获取当前系统的路径,不过request.getRealPath("/")的方法已经不推荐使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值