您的位置:首页 > 编程语言 > Java开发

struts2.0 文件上传

2012-03-05 16:20 357 查看
struts.xml配置

<action name="saveUpload" class="com.hdz.base.action.UploadAction" method="save">

   <param name="allowTypes">

       image/pjpeg,image/bmp,image/jpg,image/png,image/gif,image/jpeg,text/plain

      </param>

      <param name="savePath">d:\\upload</param>

  </action>

action配置

private File upload;

 private String uploadFileName;

 private String uploadContentType;

 private String allowTypes;

 private String savePath;

 

public String save() {

  String filterResult = filterType(this.getAllowTypes().split(","));

  if (filterResult != null) {

   setErrorInfo("您要上传的文件类型不正确");

   return filterResult;

  }

  try{

   File file = new File(getSavePath());

   if(!file.exists()){

    file.mkdir();

   }

   FileOutputStream fos = new FileOutputStream(getSavePath()+"\\"+ getUploadFileName());

   FileInputStream fis = new FileInputStream(getUpload());

   byte[] buffer = new byte[1024];

   int len = 0;

   while ((len = fis.read(buffer)) > 0) {

    fos.write(buffer, 0, len);

   }

   saveSession();

  }catch(Exception e){

   log.error(e.toString());

  }

  return SUCCESS;

 }

public String filterType(String[] types) {

  String fileType = this.getUploadContentType();

  for (String type : types) {

   if (type.equals(fileType)) {

    return null;

   }

  }

  return INPUT;

 }

jsp页面

<s:form action="saveUpload" enctype="multipart/form-data" method="post">

    标题:<s:textfield name="title"></s:textfield>

    名称:<s:file name="upload"></s:file>

    <s:submit value="提交"></s:submit>

    <s:property value="errorInfo"/>

   </s:form>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息