struts2中的文件上传

时间:2010-09-09 19:41:20

标签: struts2

我需要在struts 2中上传文件并将其存储到服务器位置,我使用谷歌没用,任何人都可以提供更好的主意。提前谢谢

2 个答案:

答案 0 :(得分:1)

谷歌,它可能有助于检查你输入的内容:它是“struts2”,没有“struts”

无论如何,你不需要谷歌,官方文档就足够了

http://struts.apache.org/2.2.1/docs/file-upload-interceptor.html

http://struts.apache.org/2.2.1/docs/handling-file-uploads.html

http://cwiki.apache.org/WW/file-upload.html

答案 1 :(得分:0)

以下是struts2文件上传的完整代码。

动作文件(fileupload.java)

package com.tutorialspoint.struts2;

import java.io.File;
import org.apache.commons.io.FileUtils;
import java.io.IOException; 

import com.opensymphony.xwork2.ActionSupport;

public class uploadFile extends ActionSupport{
   private File myFile;
   private String myFileContentType;
   private String myFileFileName;
   private String destPath;

   public String execute()
   {
      /* Copy file to a safe location */
      destPath = "C:/apache-tomcat-6.0.33/work/";

      try{
         System.out.println("Src File name: " + myFile);
         System.out.println("Dst File name: " + myFileFileName);

         File destFile  = new File(destPath, myFileFileName);
         FileUtils.copyFile(myFile, destFile);

      }catch(IOException e){
         e.printStackTrace();
         return ERROR;
      }

      return SUCCESS;
   }
   public File getMyFile() {
      return myFile;
   }
   public void setMyFile(File myFile) {
      this.myFile = myFile;
   }
   public String getMyFileContentType() {
      return myFileContentType;
   }
   public void setMyFileContentType(String myFileContentType) {
      this.myFileContentType = myFileContentType;
   }
   public String getMyFileFileName() {
      return myFileFileName;
   }
   public void setMyFileFileName(String myFileFileName) {
      this.myFileFileName = myFileFileName;
   }
}

的index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>File Upload</title>
</head>
<body>
   <form action="upload" method="post" enctype="multipart/form-data">
      <label for="myFile">Upload your file</label>
      <input type="file" name="myFile" />
      <input type="submit" value="Upload"/>
   </form>
</body>
</html>

的success.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>File Upload Success</title>
</head>
<body>
You have successfully uploaded <s:property value="myFileFileName"/>
</body>
</html>

干杯。