struts2 文件上传

package com.file.upload_download;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class fileUploadInterceptor extends ActionSupport {
 private File file;
 private String fileFileName;
 private String fileContentType;
 private String newFileName;
 private String savePath;
 public static final int BUFFERED_SIZE = 1024 * 1024;

 @Override
 public String execute() throws Exception {
  System.out.println("上传文件类型:" + fileContentType);
  System.out.println("上传文件名:" + fileFileName);
  BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
    file));
  String extension = fileFileName
    .substring(fileFileName.lastIndexOf("."));
  newFileName = new Date().getTime() + extension;
  File newFile = new File(ServletActionContext.getRequest().getRealPath(
    getSavePath()), newFileName);
  System.out.println("服务器中保存的路径及文件名:" + newFile.getAbsolutePath() + "/t"
    + newFile.getName());
  BufferedOutputStream bos = new BufferedOutputStream(
    new FileOutputStream(newFile));
  byte[] b = new byte[BUFFERED_SIZE];
  while (bis.read(b) > 0) {
   bos.write(b);
  }
  if (bos != null)
   bos.close();
  if (bis != null)
   bis.close();
  return SUCCESS;
 }

 public File getFile() {
  return file;
 }

 public void setFile(File file) {
  this.file = file;
 }

 public String getFileFileName() {
  return fileFileName;
 }

 public void setFileFileName(String fileFileName) {
  this.fileFileName = fileFileName;
 }

 public String getFileContentType() {
  return fileContentType;
 }

 public void setFileContentType(String fileContentType) {
  this.fileContentType = fileContentType;
 }

 public String getNewFileName() {
  return newFileName;
 }

 public void setNewFileName(String newFileName) {
  this.newFileName = newFileName;
 }

 public String getSavePath() {
  return savePath;
 }

 public void setSavePath(String savePath) {
  this.savePath = savePath;
 }

}

<action name="uploadfour" class="com.file.upload_download.fileUploadInterceptor">
   <interceptor-ref name="fileUpload">
    <param name="allowedTypes">image/png,image/gif,image/jpeg</param>
    <param name="maximumSize">1024</param>
   </interceptor-ref>
   <interceptor-ref name="defaultStack"></interceptor-ref>
   <param name="savePath">/upLoad</param>
   <result name="success">/four/showFour.jsp</result>
   <result name="input">/four/indexFour.jsp</result>
  </action>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值