关闭

文件上传

168人阅读 评论(0) 收藏 举报

页面的代码:

<s:form action = "uploadPro" enctype="multipart/form-data">
  <s:textfield name="title" label="文件上传"></s:textfield>
  <s:file name="upload" label="选择文件"></s:file><br/>
  <s:submit value="上传"></s:submit>
  </s:form>

 

 

action中的代码:

 

package com.ultratest.oa.employee.action;

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

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;


public class UploadAction extends ActionSupport {
 //封装文件标题请求参数的属性
 private String tiltle;
 //封装上传文件域的属性
 private File upload;
 //封装上传文件类型的属性
 private String uploadContentType;
 //封装上传文件的文件名
 private String uploadFileName;
 //直接从struts.xml文件中配置的属性,也可以手工写
 * <action name="uploadPro" class = "action.UploadAction">
  * <parma name="savePath">/upload</param>
  * 拦截器是限制上传类型和上传的大小
  * <interceptor-ref name="fileUpload">
  * <param name="allowTypes">image/png,image/gif,image/jpeg</param>
  * <param name="maximumSize">2000</param>
  * </interceptor-ref>
  * </action>
 private String savePath;
 //提供相应的setter和getter
 
 private String getSavePath()throws Exception{
  return ServletActionContext.getServletContext().getRealPath("/WEB-INF"+savePath);
 }
 
 public String getTiltle() {
  return tiltle;
 }
 
 public void setTiltle(String tiltle) {
  this.tiltle = tiltle;
 }
 
 public File getUpload() {
  return upload;
 }
 
 public void setUpload(File upload) {
  this.upload = upload;
 }
 
 public String getUploadContentType() {
  return uploadContentType;
 }
 
 public void setUploadContentType(String uploadContentType) {
  this.uploadContentType = uploadContentType;
 }
 
 public String getUploadFileName() {
  return uploadFileName;
 }
 
 public void setUploadFileName(String uploadFileName) {
  this.uploadFileName = uploadFileName;
 }
 
 public void setSavePath(String savePath) {
  this.savePath = savePath;
 }
 @Override
 public String execute() throws Exception {
  // TODO Auto-generated method stub
  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);
  }
  
  
  return super.execute();
 }
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:126221次
    • 积分:2718
    • 等级:
    • 排名:第16289名
    • 原创:106篇
    • 转载:49篇
    • 译文:1篇
    • 评论:5条
    文章分类
    最新评论