struts2实现文件上传

package com.sys.volunteer.adinfo;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

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

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.sys.volunteer.baseaction.BaseAction;
import com.sys.volunteer.common.Const;

@Controller
/* Controller为了把Action交给Spring管理 */
@Scope("prototype")
public class UploadFileAction extends BaseAction{

	// 保存文件的目录路径(通过依赖注入)
	//private String savePath = "D:/tomcat-6.0.29/webapps/VolunteerManage/";
	
	private static final int BUFFER_SIZE = 16 * 1024;
	
	private File upload;
	private String uploadContentType;
	private String uploadFileName;
	
	private String imgTitle;
	private String imgBorder;
	private String imgWidth;
	private String imgHeight;
	private String align;
	private String siteType;
	
	public String getImgWidth() {
		return imgWidth;
	}

	public void setImgWidth(String imgWidth) {
		this.imgWidth = imgWidth;
	}

	public String getImgHeight() {
		return imgHeight;
	}

	public void setImgHeight(String imgHeight) {
		this.imgHeight = imgHeight;
	}

	public String getAlign() {
		return align;
	}

	public void setAlign(String align) {
		this.align = align;
	}
	
	public String getImgTitle() {
		return imgTitle;
	}

	public void setImgTitle(String imgTitle) {
		this.imgTitle = imgTitle;
	}

	public String getImgBorder() {
		return imgBorder;
	}

	public void setImgBorder(String imgBorder) {
		this.imgBorder = imgBorder;
	}
	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;
	}

	// 自己封装的一个把源文件对象复制成目标文件对象
	private static boolean copy(File src, File dst) {
		boolean result = false;
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
			out = new BufferedOutputStream(new FileOutputStream(dst),
					BUFFER_SIZE);
			byte[] buffer = new byte[BUFFER_SIZE];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			result = false;
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	
	//上传图片
	public String execute() throws Exception {
		File srcFiles = this.getUpload();
		Long fileSize = 0L;
		if(srcFiles != null){			
			fileSize = srcFiles.length();
		}
		List<String> successFileList = new ArrayList<String>();
		Long testtime = System.currentTimeMillis();
		SimpleDateFormat fm2 = new SimpleDateFormat("yyyyMMdd");
		String folder = fm2.format(testtime);
		String filepath = getRealyPath("/upload/pictures/" + folder + "/");
		if (!new java.io.File(filepath).exists())
		{
			new java.io.File(filepath).mkdirs();
		}
		SimpleDateFormat fm = new SimpleDateFormat("yyyyMMddhhmmsss");
		String filename = fm.format(testtime);
		String fileExt = getUploadFileName().substring(getUploadFileName().lastIndexOf("."));
		getHttpServletResponse().setContentType("text/html; charset=UTF-8");
		StringBuffer buffer=new StringBuffer();
		if (fileExt.equalsIgnoreCase(".jsp") || fileExt.equalsIgnoreCase(".exe") 
				|| fileExt.equalsIgnoreCase(".js") || fileExt.equalsIgnoreCase(".asp") 
				|| fileExt.equalsIgnoreCase(".aspx") || fileExt.equalsIgnoreCase(".html") 
				|| fileExt.equalsIgnoreCase(".sql") || fileExt.equalsIgnoreCase(".class")) {
			buffer.append("<script type='text/javascript'>");
			buffer.append("alert('文件格式不正确,请重新上传!');history.back();");
			buffer.append("</script>");
			getHttpServletResponse().getWriter().print(buffer.toString());
			return null;
		}
		if("addMagic".equals(siteType)){
		    if(!fileExt.equalsIgnoreCase(".jpg")&&!fileExt.equalsIgnoreCase(".gif")){
		    	buffer.append("<script type='text/javascript'>");
				buffer.append("alert('文件格式不正确,请重新上传!');history.back();");
				buffer.append("</script>");
				getHttpServletResponse().getWriter().print(buffer.toString());
				return null;
		    }else if(fileSize > Const.MaxPictureSize){
		    	buffer.append("<script type='text/javascript'>");
				buffer.append("alert('文件大小超过5M,请重新上传!');history.back();");
				buffer.append("</script>");
				getHttpServletResponse().getWriter().print(buffer.toString());
				return null;
		    } 
		}
		File dstFile = new File(filepath+"\\"+filename+fileExt);
		if (copy(srcFiles, dstFile)) {
			successFileList.add(getUploadFileName());
		}
		getHttpServletRequest().setAttribute("successFileList", successFileList);
		String imgurl="/upload/pictures/"+folder+"/"+filename+fileExt;
		buffer.append("<script type='text/javascript'>");
		buffer.append("alert('上传文件成功!');parent.document.myform.imgurl.value='"+ imgurl +"';history.back();");
		buffer.append("</script>");
		getHttpServletResponse().getWriter().print(buffer.toString());
		return null;
	}
	
	//上传文件
	public String uploadFile() throws Exception {
		File srcFiles = this.getUpload();
		Long fileSize = 0L;
		if(srcFiles != null){			
			fileSize = srcFiles.length();
		}
		List<String> successFileList = new ArrayList<String>();
		Long testtime = System.currentTimeMillis();
		SimpleDateFormat fm2 = new SimpleDateFormat("yyyyMMdd");
		String folder = fm2.format(testtime);
		String filepath = getRealyPath("/upload/file/" + folder + "/");
		if (!new java.io.File(filepath).exists())
		{
			new java.io.File(filepath).mkdirs();
		}
		SimpleDateFormat fm = new SimpleDateFormat("yyyyMMddhhmmsss");
		String filename = fm.format(testtime);
		String fileExt = getUploadFileName().substring(getUploadFileName().lastIndexOf("."));
		getHttpServletResponse().setContentType("text/html; charset=UTF-8");
		StringBuffer buffer=new StringBuffer();
		
		if (fileExt.equalsIgnoreCase(".doc") || fileExt.equalsIgnoreCase(".docs") || fileExt.equalsIgnoreCase(".docx")
				|| fileExt.equalsIgnoreCase(".txt") || fileExt.equalsIgnoreCase(".xls") 
				|| fileExt.equalsIgnoreCase(".xlsx") || fileExt.equalsIgnoreCase(".ppt") 
				|| fileExt.equalsIgnoreCase(".ppts") || fileExt.equalsIgnoreCase(".jpg")
				|| fileExt.equalsIgnoreCase(".jpeg") || fileExt.equalsIgnoreCase(".png")
				|| fileExt.equalsIgnoreCase(".gif") || fileExt.equalsIgnoreCase(".mp3")
				|| fileExt.equalsIgnoreCase(".mp4")|| fileExt.equalsIgnoreCase(".m4v")
				|| fileExt.equalsIgnoreCase(".f4v") || fileExt.equalsIgnoreCase(".webm")
				|| fileExt.equalsIgnoreCase(".flv")|| fileExt.equalsIgnoreCase(".aac")
				|| fileExt.equalsIgnoreCase(".ogg")|| fileExt.equalsIgnoreCase(".oga")
				|| fileExt.equalsIgnoreCase(".swf")) {
			if(fileSize > Const.MaxFileSize){
		    	buffer.append("<script type='text/javascript'>");
				buffer.append("alert('文件大小超过20M,请重新上传!');history.back();");
				buffer.append("</script>");
				getHttpServletResponse().getWriter().print(buffer.toString());
				return null;
	     	} 
		   try{
			File dstFile = new File(filepath+"\\"+filename+fileExt);
			if (copy(srcFiles, dstFile)) {
				successFileList.add(getUploadFileName());
			}
			getHttpServletRequest().setAttribute("successFileList", successFileList);
			String imgurl="/upload/file/"+folder+"/"+filename+fileExt;
			buffer.append("<script type='text/javascript'>");
			buffer.append("alert('上传文件成功!');parent.document.myform.fileurl.value='"+ imgurl +"';parent.document.myform.fileName.value='"+getUploadFileName()+"';history.back();");
			buffer.append("</script>");
			getHttpServletResponse().getWriter().print(buffer.toString());
		   }catch (Exception e) {
			e.printStackTrace(System.err);
			buffer.append("<script type='text/javascript'>");
			buffer.append("alert('文件上传异常,请重新上传!');history.back();");
			buffer.append("</script>");
			getHttpServletResponse().getWriter().print(buffer.toString());
			return null;
		 }	
		}else{
			buffer.append("<script type='text/javascript'>");
			buffer.append("alert('文件格式不正确,请重新上传!');history.back();");
			buffer.append("</script>");
			getHttpServletResponse().getWriter().print(buffer.toString());
			return null;
		}
		return null;
	}
	
	//文件下载
	public  String downFile() {
			java.io.BufferedInputStream bis = null;
			java.io.BufferedOutputStream bos = null;
			try {
				String fileurl= this.getHttpServletRequest().getParameter("fileUrl").replaceAll("\\\\", "/");;
				String fileUrl = this.getHttpServletRequest().getSession().getServletContext().getRealPath("/")+fileurl.substring(1);
				String name = this.getHttpServletRequest().getParameter("fileName");
				
				String userAgent = this.getHttpServletRequest().getHeader("User-Agent");   
		        byte[] bytes = userAgent.contains("MSIE") ? name.getBytes() : name.getBytes("UTF-8"); // name.getBytes("UTF-8")处理safari的乱码问题   
		        String fileName = new String(bytes, "ISO-8859-1"); 
				
				// 客户使用保存文件的对话框:
				// fileUrl = "D:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\webapps\\VolunteerManager\\upload\\file\\20140220\\201402200531011.txt";
				//String fileName = "201402200531011.txt";
				 fileUrl = new String(fileUrl.getBytes("utf-8"), "utf-8");
				this.getHttpServletResponse().setContentType("application/x-msdownload");
				this.getHttpServletResponse().setCharacterEncoding("utf-8");
				this.getHttpServletResponse().setHeader("Content-disposition", "attachment; filename="
						+ fileName);
				// 通知客户文件的MIME类型:
				bis = new java.io.BufferedInputStream(new java.io.FileInputStream(
						(fileUrl)));
				bos = new java.io.BufferedOutputStream(this.getHttpServletResponse().getOutputStream());
				byte[] buff = new byte[2048];
				int bytesRead;
				int i = 0;

				while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
					bos.write(buff, 0, bytesRead);
					i++;
				}
				bos.flush();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (bis != null) {
					try {
						bis.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					bis = null;
				}
				if (bos != null) {
					try {
						bos.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					bos = null;
				}
			}
        return null;
    }

	
	//编辑器上传
	public String uploadEdit() throws Exception {
		
		String fileExt = getUploadFileName().substring(getUploadFileName().lastIndexOf("."));
		JSONObject obj = new JSONObject();
		if (fileExt.equalsIgnoreCase(".doc") || fileExt.equalsIgnoreCase(".docs")
				|| fileExt.equalsIgnoreCase(".txt") || fileExt.equalsIgnoreCase(".xls") 
				|| fileExt.equalsIgnoreCase(".xlsx") || fileExt.equalsIgnoreCase(".ppt") 
				|| fileExt.equalsIgnoreCase(".ppts") || fileExt.equalsIgnoreCase(".jpg")
				|| fileExt.equalsIgnoreCase(".jpeg") || fileExt.equalsIgnoreCase(".png")
				|| fileExt.equalsIgnoreCase(".gif") || fileExt.equalsIgnoreCase(".mp3")
				|| fileExt.equalsIgnoreCase(".mp4")|| fileExt.equalsIgnoreCase(".m4v")
				|| fileExt.equalsIgnoreCase(".f4v") || fileExt.equalsIgnoreCase(".webm")
				|| fileExt.equalsIgnoreCase(".flv")|| fileExt.equalsIgnoreCase(".aac")
				|| fileExt.equalsIgnoreCase(".ogg")|| fileExt.equalsIgnoreCase(".oga")
				|| fileExt.equalsIgnoreCase(".swf")
				){

			File srcFiles = this.getUpload();
			List<String> successFileList = new ArrayList<String>();
			Long testtime = System.currentTimeMillis();
			SimpleDateFormat fm2 = new SimpleDateFormat("yyyyMMdd");
			String folder = super.getHttpServletRequest().getParameter("folder");
			if(StringUtils.isEmpty(folder)){
				folder = fm2.format(testtime);
			}			
			String filepath = getRealyPath("/upload/" + folder + "/");
			if (!new java.io.File(filepath).exists()) {
				new java.io.File(filepath).mkdirs();
			}
			SimpleDateFormat fm = new SimpleDateFormat("yyyyMMddhhmmsss");
			String filename = fm.format(testtime);
			File dstFile = new File(filepath + "\\" + filename + fileExt);
			if (copy(srcFiles, dstFile)) {
				successFileList.add(getUploadFileName());
			}
			// getHttpServletRequest().setAttribute("successFileList",
			// successFileList);
			String imgurl = getHttpServletRequest().getContextPath() + "/upload/" + folder + "/" + filename + fileExt;
			obj.element("error", 0);
			obj.element("url", imgurl);
			this.writeAjaxStr(obj.toString());
			return null;
		} else {
			obj.element("error", -3);
			obj.element("message", "文件格式不正确,请重新上传!");
			this.writeAjaxStr(obj.toString());
			return null;
		}

	}
	
	

	public HttpServletRequest getHttpServletRequest() {
		return ServletActionContext.getRequest();
	}
	public ServletContext getServletContext() {
		return ServletActionContext.getServletContext();
	}
	
	public HttpServletResponse getHttpServletResponse() {
		return ServletActionContext.getResponse();
	}
	
	public String getRealyPath(String path) {
		return getServletContext().getRealPath(path);
	}

	public String getSiteType() {
		return siteType;
	}

	public void setSiteType(String siteType) {
		this.siteType = siteType;
	}
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值