JAVA文件上传工具类

package com.ccxe.trust.proselect.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.ccxe.common.util.FileUtil;
import com.ccxe.common.util.StringUtil;
import com.ccxe.common.web.BaseAction;
import com.ccxe.trust.proselect.pojo.BAtta;
import com.ccxe.trust.proselect.service.IProSelectCommonService;
import com.ccxe.trust.proselect.util.ProConstants;
import com.ccxe.trust.proselect.util.TrustConfig;

/**
 * 附件上传Action
 * 
 * 
 * Dec 3, 2013
 */
public class AttachmentUploadAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private Logger log = Logger.getLogger(AttachmentUploadAction.class);
	private IProSelectCommonService proSelectCommonService;
	
	private File[] upload;// 实际上传文件
	private String[] uploadContentType; // 文件的内容类型
	private String[] uploadFileName; // 上传文件名
	private List<String> attType;
	private BAtta attachment;
	//错误信息
	private String msg = "";
	
	/**
	 * 响应操作:上传各项附件
	 */
	public String upload() {
		try {
			JSONArray array = new JSONArray();
			JSONObject json = null;
			if(null != upload) {
				for(int i = 0;i<upload.length;i++) {
					if(this.upload[i].length() < ProConstants.FILE_SIZE) {
						if(this.proSelectCommonService.checkAttachment(attachment.getRelaId(), attachment.getAttCata(), attType.get(i)) == 0){
							BAtta att = null;
							String ioFileName = FileUtil.writerFile(upload[i],uploadFileName[i]);
							if(StringUtil.isNotNull(ioFileName)) {
								att = new BAtta();
								att.setRelaId(attachment.getRelaId());
								att.setAttTitle(uploadFileName[i]);
								att.setAttSrcTitle(uploadFileName[i]);
								att.setAttCata(attachment.getAttCata());
								att.setAttPath(ioFileName);
								att.setAttType(attType.get(i));
								att.setStatus(ProConstants.DC_BL_STATUS.BOOL_YES);
								att.setCreateUser(this.getSessionUserInfo().getUserID());
								att.setUpdateUser(this.getSessionUserInfo().getUserID());
								att.setAttSeqNum(i+1);
								this.getProSelectCommonService().saveProAttachment(att);
							}
						}else {  //此类别附件已存在
							json = new JSONObject();
							json.put("msg","【" + attType.get(i) + "】附件已存在,可以删除以后再上传.");
							array.add(json);
						}
					}else {   //上传文件大于限制大小
						json = new JSONObject();
						json.put("msg", "【" + attType.get(i) + "】上传文件超过系统限制" + ProConstants.FILE_SIZE / (1024*1024) + "M.");
						array.add(json);
					}
				}
			}
			msg = array.size() > 0 ? java.net.URLEncoder.encode(array.toString(),"UTF-8"): "";
		} catch (Exception e){
			e.printStackTrace();
			return INPUT;
		}
		return SUCCESS;
	}

	/**
	 * 响应操作:删除附件
	 * @return
	 */
	public String removeAttachment() {
		PrintWriter out = null;
		JSONObject json = new JSONObject();
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html;charset=UTF-8");
			out = response.getWriter();
			
			String attId = (String)this.getAppRequestParameterByName("attId");
			if(StringUtil.isNotNull(attId)) {
				this.proSelectCommonService.deleteProAttachment(attId);
			}
			json.put("status","success");
			json.put("id", attId);
			out.print(json.toString());
		}catch(Exception e) {
			log.error("删除附件出错",e);
			json.put("status","error");
			out.print(json.toString());
		}finally {
			if (out != null) {
				out.flush();
				out.close();
			}
		}
		return null;
	}
	
	private String fileName;// 初始的通过param指定的文件名属性    
    private String inputPath;// 指定要被下载的文件路径
	/**
	 * 响应操作:下载附件
	 * @return
	 */
    public String download() {
    	try{
    		WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
			TrustConfig  trustConfig =  (TrustConfig)wac.getBean(ProConstants.configBeanName);//模块配置文件
			String attId = (String)this.getAppRequestParameterByName("attId");
			if(StringUtil.isNotNull(attId)) {
				this.attachment = this.getProSelectCommonService().fetchAttachment(attId);
				if(null != attachment) {
					//inputPath =  trustConfig.getTrustProselectCustFilePath()+"/" +attachment.getAttPath();
					inputPath =  trustConfig.getTrustProselectCustFilePath()+ attachment.getAttPath();//20140528 zhaocg modified:配置文件中统一加了/
					//fileName = java.net.URLEncoder.encode(attachment.getAttSrcTitle(),"UTF-8");
					fileName = attachment.getAttSrcTitle();
				}
			}
    		File file = new File(inputPath);
    		if(!file.exists()) {
    			this.getAppRequest().setAttribute("errorMsg","下载的附件不存在或已被删除。");
    			return ERROR;
    		}
    	}catch(Exception e){
    		log.error("下载附件出错",e);
    		return ERROR;
    	}
    	return SUCCESS;
    }
    public String getDownloadFileName() {
		String downFileName = fileName;
		try {
			HttpServletRequest request = getAppRequest();
			String agent = request.getHeader("USER-AGENT");
			if(null != agent && -1 != agent.indexOf("theworld")){	//世界之窗
				downFileName = new String(downFileName.getBytes("gb2312"), "ISO8859-1");    //解决下载的文件名中含有小括号转变义符%28%29
			}else if(null != agent && -1 != agent.indexOf("MSIE 8.0")){	//IE8
				//downFileName = java.net.URLDecoder.decode(downFileName,"UTF-8");
				downFileName =URLEncoder.encode(downFileName, "UTF-8").replace("+","%20"); 
			}else if(null != agent && -1 != agent.indexOf("MSIE 7.0") && -1 != agent.indexOf("SE 2.X MetaSr 1.0")){	//sogo浏览器
				downFileName =URLEncoder.encode(downFileName, "UTF-8").replace("+","%20"); 
			}else if(null != agent && (-1 != agent.indexOf("SV1") || -1 != agent.indexOf("360SE"))){	//360安全浏览器
				downFileName = new String(downFileName.getBytes("gb2312"), "ISO8859-1"); 
			}else if(null != agent && -1 != agent.indexOf("Chrome")){	//google
				//fileName = URLEncoder.encode(downFileNameCN,"UTF-8").replace("+","%20");	
				downFileName = new String(downFileName.getBytes("gb2312"), "ISO8859-1"); //解决下载的文件名中含有小括号转变义符%28%29
			}else if(null != agent && -1 != agent.indexOf("Firefox")){	//Firefox
				//downFileName = java.net.URLDecoder.decode(downFileName,"UTF-8");
				downFileName = new String(downFileName.getBytes("gb2312"), "ISO8859-1");
			}else if(null != agent && -1 != agent.indexOf("Safari")){	//Safari 
				downFileName = new String(downFileName.getBytes("UTF-8"), "ISO8859-1");
			}else if(null != agent && -1 != agent.indexOf("Opera")){	//Opera
				downFileName = new String(downFileName.getBytes("UTF-8"), "ISO8859-1");
			}else {	//其它浏览器
				downFileName = new String(downFileName.getBytes("gb2312"), "ISO8859-1");
			}
		}catch(UnsupportedEncodingException e) {    
           e.printStackTrace();    
		}    
		return downFileName;
    }
	public InputStream getInputStream() throws Exception {
    	InputStream inputStream = new FileInputStream(new File(inputPath));
    	return inputStream;
    }
	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 List<String> getAttType() {
		return attType;
	}
	public void setAttType(List<String> attType) {
		this.attType = attType;
	}
	public BAtta getAttachment() {
		return attachment;
	}
	public void setAttachment(BAtta attachment) {
		this.attachment = attachment;
	}
	public IProSelectCommonService getProSelectCommonService() {
		return proSelectCommonService;
	}
	public void setProSelectCommonService(
			IProSelectCommonService proSelectCommonService) {
		this.proSelectCommonService = proSelectCommonService;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
}
<!-- 附件 -->
		<action name="att_*" class="com.ccxe.trust.proselect.action.AttachmentUploadAction" method="{1}">
			<result type="redirect">/proSelect/proSetup_fetchProAtt.action?proId=${attachment.relaId}&msg=${msg}</result>
		</action>
		<!-- 附件下载 -->
		<action name="downloadAtt" class="com.ccxe.trust.proselect.action.AttachmentUploadAction" method="download">  
	            <param name="inputPath">${inputPath}</param>  
	            <!-- 初始文件名 -->  
	            <param name="fileName">${fileName}</param>  
	            <result name="success" type="stream">  
	                <param name="contentType">application/octet-stream;charset=UTF-8</param>  
	                <param name="inputName">inputStream</param>  
	                <!-- 使用经过转码的文件名作为下载文件名,downloadFileName属性对应action类中的方法 getDownloadFileName() -->  
	                <param name="contentDisposition">attachment;filename="${downloadFileName}"</param>  
	                <param name="bufferSize">4096</param>  
	            </result>
        </action>


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值