UploadDownloadUtil

package com.hzf.util;

import java.beans.PropertyDescriptor;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadDownloadUtil {
	/**
	 * 处理带有multipart/form-data支持文件上传的表单 Description:
	 */
	public String[] uploadFile(HttpServletRequest request,int diskmax,String temp,String path,int max, Affix affix) throws Exception{
		System.out.println("上传中*********************************************");
		List list=new ArrayList();
		List itemList = new ArrayList();
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart == false)
			return null;

			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(diskmax);

			File tempFile = new File(temp);
			if (!tempFile.exists())
				tempFile.mkdir();

			factory.setRepository(tempFile);

			ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setSizeMax(max);
            List items = null;

			try {
				items = upload.parseRequest(request);
			} catch (Exception e) {
				e.printStackTrace();
				throw new HTMLActionException("文件大小不能超过"+max/1024/1024+"M");
			}

			Iterator iter = items.iterator();

//			先处理表单中的所有普通参数
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					processFormField(item,affix);
				} else {
					itemList.add(item);
				}
			}

//			根据不同附件实体,设置不同的上传路径
			path = affix.resetPath(path);

//			处理表单中的文件参数
			for(int i = 0 ;i<itemList.size();i++){
				list.add(processUploadedFile(request,(FileItem)itemList.get(i),path));
			}


		return (String[])list.toArray(new String[list.size()]);
	}
	/**
	 * 处理表单中得普通变量 ,此时获取不到文件名称
	 */
	public void processFormField(FileItem item, Object obj){
		String fieldName = item.getFieldName();

		Class c = obj.getClass();
		Field[] fs = c.getDeclaredFields();
		try{
			String value = new String(URLDecoder.decode(item.getString(),"utf-8"));
			for(int i = 0 ; i < fs.length;i++){
				if(fieldName.equals(fs[i].getName())){
					PropertyDescriptor p = new PropertyDescriptor(fs[i].getName(), c);
					Method m = p.getWriteMethod();
					m.invoke(obj, new Object[] { CastUtil.castValue(value, fs[i].getType()) });
					break;
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 处理表单中文件 Description:
	 *
	 * @param item
	 * @throws Exception
	 * @author 孙钰佳
	 * @param ev
	 * @since:Sep 3, 2007 1:06:58 PM
	 */
	public String processUploadedFile(HttpServletRequest request, FileItem item, String path) throws Exception {
		String fileName = item.getName();
		fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
		System.out.println("fileName:" + fileName);

		String realPath=request.getRealPath("/");
		File uploadFile = new File(realPath + path);
		if (!uploadFile.exists())
			uploadFile.mkdirs();
		String filePath = path + fileName;

		File uploadedFile = new File(realPath + filePath);
		item.write(uploadedFile);
		return filePath;
	}

	/**
	 * @Description:文件下载
	 */
	public void downLoad(String filePath, HttpServletResponse response) throws Exception {
        File f = new File(filePath);

		if (!f.exists()) {
			response.setContentType("text/html");
			response.setCharacterEncoding("gbk");
			PrintWriter printWriter = response.getWriter();
			printWriter.println(f.getName()+"文件不存在");
			printWriter.flush();
			printWriter.close();
		}

		byte[] buf = new byte[1024];
		int len = 0;

		response.reset(); // 一定要重置response
		response.setContentType("application/x-msdownload");
		try {
			response.setHeader("Content-disposition", "attachment; filename=" + new String(f.getName().getBytes("gb2312"), "iso8859-1"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			response.setHeader("Content-disposition", "attachment; filename=" + f.getName());
		}

		BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
		OutputStream out = response.getOutputStream();
		while ((len = br.read(buf)) > 0) {
			out.write(buf, 0, len);
			out.flush();
		}
		br.close();
		out.close();

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值