亲宝软件园·资讯

展开

Struts2上传文件 Struts2实现上传单个文件功能

我扶奶奶过哈登 人气:0
想了解Struts2实现上传单个文件功能的相关内容吗,我扶奶奶过哈登在本文为您仔细讲解Struts2上传文件的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Struts2上传文件,Struts2上传单个文件,Struts2上传,下面大家一起来学习吧。

upload.jsp 这个页面选择提交文件,提交到uploadImage.action

<%@ page language="java" contentType="text/html; charset=utf-8"
  pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
  <form action="uploadImage.action" enctype="multipart/form-data" method="post">
    please select the file:<input type="file" name="upload">
    <input type="submit" value="上传文件">
  </form>
</body>
</html>

FileUploadAction.java 将传来的file进行处理

package action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport{
  private File upload;
  private String uploadFileName;
  private String uploadContentType;


  public File getUpload() {
    return upload;
  }


  public void setUpload(File upload) {
    this.upload = upload;
  }


  public String getUploadFileName() {
    return uploadFileName;
  }


  public void setUploadFileName(String uploadFileName) {
    this.uploadFileName = uploadFileName;
  }


  public String getUploadContentType() {
    return uploadContentType;
  }


  public void setUploadContentType(String uploadContentType) {
    this.uploadContentType = uploadContentType;
  }


  public String execute(){
    System.out.println(upload);
    System.out.println(uploadContentType);
    System.out.println(uploadFileName);

    String savePath = ServletActionContext.getServletContext().getRealPath("/upload/"+this.uploadFileName);
    System.out.println(savePath);

    try{
      FileInputStream fis = new FileInputStream(upload);
      FileOutputStream fos = new FileOutputStream(savePath);
      IOUtils.copy(fis, fos);
      fos.flush();
      fos.close();
      fis.close();
    }catch(Exception e){
      e.printStackTrace();
    }
    return "success";
  }
}

uploadFileName和uploadContentType,这两个属性分别用于封装上传文件的文件名、上传文件的文件类型

Struts.xml配置

<action name="uploadImage" class="action.FileUploadAction">
 <result name="success">uploadSuccess.jsp</result>
 <result name="input">uploadError.jsp</result>
</action>

成功失败界面随便写一个就行了,不贴了。

加载全部内容

相关教程
猜你喜欢
用户评论