文件上传

页面的代码:

<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();
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值