JAVA EE项目常用之 struts1.2 文件上传的两种方法

在上传的jsp页面:

<form action="fileShare.do?method=addFileShare" method="post" enctype="multipart/form-data" name="form1" id="form1">
	 	  <table  class="cx_table2" cellpadding="0" cellspacing="0">
	 			<tr>
	 				<th width="20%">
 						<span style="color: red">*</span>
	 					添加资料:
	 				</th>
	 				<td>
	 					<input type="file" name="file" id="file" />
	 					<span id="checkFile"></span>
	 				</td>
	 			</tr>
	 			<tr>
	 				<th width="20%"><span style="color: red">*</span>资料文件名:</th>
	 				<td>
	 					<input type="text" name="file_name" id="file_name" style="width: 60%"/>
	 					<input type="button"  class="btn_bg" id="chkBox" οnclick="setFileName();" value="默认名"/>
	 					<span id="checkFileName"></span>
	 				</td>
	 			</tr>
	 			<tr>
	 				<th width="20%">
	 					资料描述:
	 				</th>
	 				<td>
	 					<textarea rows="15" style="height: 110px;" class="textarea1" name="file_description" id="file_description"></textarea>
	 					<br />
	 					<span id="checkFileDescription"></span>
	 				</td>
	 			</tr>
	 			<tr>
		 			<td colspan="2" style="padding:0">
			 			<div class="btn_nav_bg">
			 			<input type="hidden" name="<%=Token.TOKEN_STRING_NAME%>"
											value="<%=Token.getTokenString(session)%>" />
			 			<input type="button" class="btn_bg" οnclick="doSub()" value="提 交"/>
			 			<input type="reset" class="btn_bg" value="重 置"/>
			 			<input type="hidden" value="${power }" id="power" name="power"/>
			 			<input type="button" class="btn_bg" value="关 闭"	οnclick="window.close();" />
			 			</div>
		 			</td>
	 			</tr>
	 		</table>
</form>


form表单 需要有属性 enctype="multipart/form-data"
写好input type="file" 和form action属性的值  即路径请求 到struts-config.xml 文件


需要有个form-bean:

package com.woyi.struts.form;

import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;

public class FileShareForm extends ActionForm{
 private static final long serialVersionUID = 1L;
 private String fileName;//上传文件的名称
     private String fileSize;//上传文件的大小
     private String uploadTime;//上传文件的日期
     private FormFile file;//上传文件
    
    
 public String getFileName() {
  return fileName;
 }
 public void setFileName(String fileName) {
  this.fileName = fileName;
 }
 public String getFileSize() {
  return fileSize;
 }
 public void setFileSize(String fileSize) {
  this.fileSize = fileSize;
 }
 public String getUploadTime() {
  return uploadTime;
 }
 public void setUploadTime(String uploadTime) {
  this.uploadTime = uploadTime;
 }
 public FormFile getFile() {
  return file;
 }
 public void setFile(FormFile file) {
  this.file = file;
 }
}


 

input type="file" 的input 标签 name 属性的值 与FileShareForm FormFile 类型的属性 名称一样。

struts-config.xml 文件中应用的内容
<form-beans>
<form-bean name="fileShareForm" type="com.woyi.struts.form.FileShareForm"></form-bean>
</form-beans>

<action path="/fileShare"
      parameter="method"
      scope="request"
      name="fileShareForm"
      type="com.woyi.struts.action.FileShareAction">
     <forward name="toAdd" path="/back/fileShare/addFileShare.jsp"></forward>
</action>

通过 fileShareForm这个bean 把文件对象 传到form表单action属性中的路径指定的方法(像com.woyi.struts.action.FileShareAction)
ActionForm form 这个参数里面。然后在方法里面处理

处理的过程:
1 用ActionForm form 这个参数 获得上传过来的文件对象 。
2 获得一个真实的文件路径 。用 new file() 把这个 文件路径 new 出来
3 用 new 的文件对象 获得路径 待上 文件名 后缀名。
4 用 new FileOutputStream(fullFileName);
5 用 InputStream streamIn = file.getInputStream();//创建读取用户上传文件的对象的流
int bytesRead = 0;
         byte[] buffer = new byte[8192];
         while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
          streamOut.write(buffer, 0, bytesRead);
         }
         streamOut.close();
         streamIn.close();
         file.destroy();

处理上传的代码:

/**
	 * 获取小写的后缀名
	 */
	private String getType(String string){
		String type = "";
		int i = string.lastIndexOf(".");//最后一个点的下标
        if(i != -1){
        	type = string.substring(i);
        }
		return type.toLowerCase();
	}
/**
     * 根据后缀名和系统时间按生成一个字节量不超过n的字符串
     * @param type 后缀名
     */
    private String getSystemFileName(String type,int n) {
        String systemFileName = System.currentTimeMillis()+getNCharacter(7) + type;
        systemFileName = cut(systemFileName,n,"gbk");
        return systemFileName;
    }



public ActionForward addFileShare(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response){

        FileShareForm fileShareForm = (FileShareForm) form;
        //FormFile用于指定存取文件的类型
        FormFile file = fileShareForm.getFile(); //获取当前的文件
        String type = getType(file.getFileName());
        String fileSize = getSize(file.getFileSize());
        // 获得系统的绝对路径  
        String realPath = servlet.getServletContext().getRealPath("/upload/filesShared");
        //处理客户是否输入后缀名
       if(!type.equalsIgnoreCase(getType(fileName))){
         fileName = fileName + type;
        } 
        File uploadFile = new File(realPath);   //指定上传文件的位置
        if (!uploadFile.exists() && uploadFile != null) {  //判断指定路径dir是否存在,不存在则创建路径
          uploadFile.mkdirs();
        }
        systemFileName = getSystemFileName(type,25);
        String fullFileName = uploadFile.getPath() + "//" + systemFileName;
       try{
         OutputStream streamOut = new FileOutputStream(fullFileName);
           
         InputStream streamIn = file.getInputStream();//创建读取用户上传文件的对象
           
         int bytesRead = 0;
         byte[] buffer = new byte[8192];
         while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
          streamOut.write(buffer, 0, bytesRead);
         }
         streamOut.close();
         streamIn.close();
         file.destroy();
  } catch (Exception e) {
   e.printStackTrace();
   request.setAttribute("message", "接收文件失败");
   return mapping.findForward("toAdd");
  }

}


 

方法二:(只要 调用的方法里 有request 对象 即可)


 

package ueditor;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.FileUploadBase.InvalidContentTypeException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.util.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;


import sun.misc.BASE64Decoder;
import javax.servlet.http.HttpServletRequest;
/**
 * UEditor文件上传辅助类
 *
 */
public class Uploader {
 // 输出文件地址
 private String url = "";
 // 上传文件名
 private String fileName = "";
 // 状态
 private String state = "";
 // 文件类型
 private String type = "";
 // 原始文件名
 private String originalName = "";
 // 文件大小
 private String size = "";

 private HttpServletRequest request = null;
 private String title = "";

 // 保存路径
 private String savePath = "upload";
 // 文件允许格式
 private String[] allowFiles = { ".rar", ".doc", ".docx", ".zip", ".pdf",".txt", ".swf", ".wmv", ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
 // 文件大小限制,单位KB
 private int maxSize = 10000;
 
 private HashMap<String, String> errorInfo = new HashMap<String, String>();

 public Uploader(HttpServletRequest request) {
  this.request = request;
  HashMap<String, String> tmp = this.errorInfo;
  tmp.put("SUCCESS", "SUCCESS"); //默认成功
  tmp.put("NOFILE", "未包含文件上传域");
  tmp.put("TYPE", "不允许的文件格式");
  tmp.put("SIZE", "文件大小超出限制");
  tmp.put("ENTYPE", "请求类型ENTYPE错误");
  tmp.put("REQUEST", "上传请求异常");
  tmp.put("IO", "IO异常");
  tmp.put("DIR", "目录创建失败");
  tmp.put("UNKNOWN", "未知错误");
 
 }

 public void upload() throws Exception {
  boolean isMultipart = ServletFileUpload.isMultipartContent(this.request);
  if (!isMultipart) {
   this.state = this.errorInfo.get("NOFILE");
   return;
  }
  DiskFileItemFactory dff = new DiskFileItemFactory();
  String savePath = this.getFolder(this.savePath);
  dff.setRepository(new File(savePath));
  try {
   ServletFileUpload sfu = new ServletFileUpload(dff);
   sfu.setSizeMax(this.maxSize * 1024);
   sfu.setHeaderEncoding("gbk");
   FileItemIterator fii = sfu.getItemIterator(this.request);
   while (fii.hasNext()) {
    FileItemStream fis = fii.next();
    if (!fis.isFormField()) {
     this.originalName = fis.getName().substring(fis.getName().lastIndexOf(System.getProperty("file.separator")) + 1);
     if (!this.checkFileType(this.originalName)) {
      this.state = this.errorInfo.get("TYPE");
      continue;
     }
     this.fileName = this.getName(this.originalName);
     this.type = this.getFileExt(this.fileName);
     this.url = savePath + "/" + this.fileName;
     BufferedInputStream in = new BufferedInputStream(fis.openStream());
     FileOutputStream out = new FileOutputStream(new File(this.getPhysicalPath(this.url)));
     BufferedOutputStream output = new BufferedOutputStream(out);
     Streams.copy(in, output, true);
     this.state=this.errorInfo.get("SUCCESS");
     //UE中只会处理单张上传,完成后即退出
     break;
    } else {
     String fname = fis.getFieldName();
     //只处理title,其余表单请自行处理
     if(!fname.equals("pictitle")){
      continue;
     }
                    BufferedInputStream in = new BufferedInputStream(fis.openStream());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuffer result = new StringBuffer();  
                    while (reader.ready()) {  
                        result.append((char)reader.read());  
                    }
                    this.title = new String(result.toString().getBytes(),"gbk");
                    reader.close();  
                    
    }
   }
  } catch (SizeLimitExceededException e) {
   this.state = this.errorInfo.get("SIZE");
  } catch (InvalidContentTypeException e) {
   this.state = this.errorInfo.get("ENTYPE");
  } catch (FileUploadException e) {
   this.state = this.errorInfo.get("REQUEST");
  } catch (Exception e) {
   this.state = this.errorInfo.get("UNKNOWN");
  }
 }
 
 

 /**
  * 文件类型判断
  * 
  * @param fileName
  * @return
  */
 private boolean checkFileType(String fileName) {
  Iterator<String> type = Arrays.asList(this.allowFiles).iterator();
  while (type.hasNext()) {
   String ext = type.next();
   if (fileName.toLowerCase().endsWith(ext)) {
    return true;
   }
  }
  return false;
 }

 /**
  * 获取文件扩展名
  * 
  * @return string
  */
 private String getFileExt(String fileName) {
  return fileName.substring(fileName.lastIndexOf("."));
 }

 /**
  * 依据原始文件名生成新文件名
  * @return
  */
 private String getName(String fileName) {
  Random random = new Random();
  return this.fileName = "" + random.nextInt(10000)
    + System.currentTimeMillis() + this.getFileExt(fileName);
 }

 /**
  * 根据字符串创建本地目录 并按照日期建立子目录返回
  * @param path 
  * @return 
  */
 private String getFolder(String path) {
  SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
  path += "/" + formater.format(new Date());
  File dir = new File(this.getPhysicalPath(path));
  if (!dir.exists()) {
   try {
    dir.mkdirs();
   } catch (Exception e) {
    this.state = this.errorInfo.get("DIR");
    return "";
   }
  }
  return path;
 }

 /**
  * 根据传入的虚拟路径获取物理路径
  * 
  * @param path
  * @return
  */
 private String getPhysicalPath(String path) {
  String servletPath = this.request.getServletPath();
  String realPath = this.request.getSession().getServletContext()
    .getRealPath(servletPath);
  return new File(realPath).getParent() +"/" +path;
 }

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

 public void setAllowFiles(String[] allowFiles) {
  this.allowFiles = allowFiles;
 }

 public void setMaxSize(int size) {
  this.maxSize = size;
 }

 public String getSize() {
  return this.size;
 }

 public String getUrl() {
  return this.url;
 }

 public String getFileName() {
  return this.fileName;
 }

 public String getState() {
  return this.state;
 }
 
 public String getTitle() {
  return this.title;
 }

 public String getType() {
  return this.type;
 }

 public String getOriginalName() {
  return this.originalName;
 }
}


 

用 new Uploader.upload() 即可

 

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值