首页 > 代码库 > Struts文件上传机制

Struts文件上传机制

 

 <action name="fileUp" class="FileUpload.FileUpload">
            <result>/message.jsp</result>
        </action>

 

 

单文件上传

1.Action类

技术分享

 

 1 package FileUpload;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileNotFoundException;
 6 import java.io.FileOutputStream;
 7 
 8 import javax.servlet.ServletContext;
 9 
10 import org.apache.struts2.ServletActionContext;
11 
12 import com.opensymphony.xwork2.ActionSupport;
13 
14 public class FileUpload  extends ActionSupport{
15 
16     private File fileName;
17     private String fileNameContentType;
18     private String fileNameFileName;
19     
20     public String execute() throws Exception{
21         
22         ServletContext servletContext = ServletActionContext.getServletContext();
23         String dir = servletContext.getRealPath("/files/"+fileNameFileName);
24         System.out.println(dir);

25 FileOutputStream outputStream = new FileOutputStream(dir); 26 FileInputStream inputStream = new FileInputStream(fileName); 27 byte[] buffer = new byte[1024]; 28 int len = 0; 29 // 从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中.读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1。 30 while((len = inputStream.read(buffer))!=-1){ 31 // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此文件输出流。 32 outputStream.write(buffer, 0, len); 33 } 34 inputStream.close(); 35 outputStream.close();

36 return SUCCESS; 37 } 38 39 public File getFileName() { 40 return fileName; 41 } 42 43 public void setFileName(File fileName) { 44 this.fileName = fileName; 45 } 46 47 public String getFileNameContentType() { 48 return fileNameContentType; 49 } 50 51 public void setFileNameContentType(String fileNameContentType) { 52 this.fileNameContentType = fileNameContentType; 53 } 54 55 public String getFileNameFileName() { 56 return fileNameFileName; 57 } 58 59 public void setFileNameFileName(String fileNameFileName) { 60 this.fileNameFileName = fileNameFileName; 61 } 62 63 64 65 }

 2.

技术分享

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>Insert title here</title>
 6 </head>
 7 <body>
 8 
 9 <form action="/Struts2FileUpload/fileUp.action" method="post" enctype ="multipart/form-data">
10 
11 <input type="file" name="fileName" >
12 <input type="submit" value="提交">
13 </form>
14 
15 </body>
16 </html>

 3.

 <action name="fileUp" class="FileUpload.FileUpload">
            <result>/message.jsp</result>
 </action>

 

Struts文件上传机制