文件上传下载整理

jar包
<!-- 文件上传下载 -->
	<dependency>
	    <groupId>commons-fileupload</groupId>
	    <artifactId>commons-fileupload</artifactId>
	    <version>1.3.1</version>
	</dependency>
spring配置
<!-- 上传下载的配置 --> 
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    	 <property name="maxUploadSize" value="10240000000"/>
		 <property name="defaultEncoding" value="utf-8"/>
	</bean>

controller接收参数@RequestParam("files")MultipartFile[] files

页面提交时要在form表单加上enctype="multipart/form-data"

文件上传工具类以及删除工具

public class UploadUtil {
	//这个给定上传下载的文件数组和路径就可以完成上传工作
	public static Map<String,String> upFile(String path,MultipartFile[] files){
		Map<String,String> map=new HashMap<String,String>();
		//先判断当前的路径是否存在没有就建造
		File file = new File(path);
		if(!file.exists()){
			file.mkdirs();
		}
		//遍历上传资料
		if(files.length!=0){
			for (int i = 0; i < files.length; i++) {
				try {
					String oldName=files[i].getOriginalFilename();
					String format = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());	
					String endPath=path+File.separator+format+oldName;
					files[i] .transferTo(new File(endPath));
					//添加文件存储的路劲和文件的名称
					map.put(oldName,endPath);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return map;
	}
	//删除文件的方法 可以是文件或者文件夹
	public static void deleteFilePath(String path){
		File file = new File(path);
		if(file.exists()){
			deleteFile(file);
		}
	}
	//删除文件的辅助方法
	public static void deleteFile(File f){
		if(f.isFile()){
			f.delete();
		}
		if(f.isDirectory()){
			File[] files = f.listFiles();
			for (File file : files) {
				if(file.isFile()){file.delete();}
				if(file.isDirectory()){deleteFile(file);}
			}
		}
	}
}
下载工具类
/**
 * 下载工具类
 */
public class DownLoadUtil {
	public static void down(HttpServletRequest request,
			HttpServletResponse response, String path, String fileName) {
		response.setContentType("text/html;charset=utf-8");
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}

		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			long fileLength = new File(path).length();
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-disposition", "attachment;filename="
					+ new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
			response.setHeader("Content-Length", String.valueOf(fileLength));
			bis = new BufferedInputStream(new FileInputStream(path));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

}
打包下载工具类
public class PackDownload {
	//文件打包下载
    public static HttpServletResponse downLoadFiles(File file,List<File> files,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            /**创建一个临时压缩文件,
             * 我们会把文件流全部注入到这个文件中
             * 这里的文件你可以自定义是.rar还是.zip*/
            if (!file.exists()){   
                file.createNewFile();   
            }
            response.reset();
            //response.getWriter()
            //创建文件输出流
            FileOutputStream fous = new FileOutputStream(file);   
            /**打包的方法我们会用到ZipOutputStream这样一个输出流,
             * 所以这里我们把输出流转换一下*/
           ZipOutputStream zipOut 
            = new ZipOutputStream(fous);
            /**这个方法接受的就是一个所要打包文件的集合,
             * 还有一个ZipOutputStream*/
           zipFile(files, zipOut);
            zipOut.close();
            fous.close();
           return downloadZip(file,response);
        }catch (Exception e) {
                e.printStackTrace();
            }
            /**直到文件的打包已经成功了,
             * 文件的打包过程被我封装在FileUtil.zipFile这个静态方法中,
             * 稍后会呈现出来,接下来的就是往客户端写数据了*/
           
     
        return response ;
    }

  /**
     * 把接受的全部文件打成压缩包 
     * @param List<File>;  
     * @param org.apache.tools.zip.ZipOutputStream  
     */
    public static void zipFile
            (List files,ZipOutputStream outputStream) {
        int size = files.size();
        for(int i = 0; i < size; i++) {
            File file = (File) files.get(i);
            zipFile(i,file, outputStream);
        }
    }

    public static HttpServletResponse downloadZip(File file,HttpServletResponse response) {
        try {
        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();

        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");

//如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
        response.setHeader("Content-Disposition", "attachment;filename=" +URLEncoder.encode(file.getName(), "UTF-8"));
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        } catch (IOException ex) {
        ex.printStackTrace();
        }finally{
             try {
                    File f = new File(file.getPath());
                    f.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
        }
        return response;
    }

/**  
     * 根据输入的文件与输出流对文件进行打包
     * @param File
     * @param org.apache.tools.zip.ZipOutputStream
     */
    public static void zipFile(int a,File inputFile,
            ZipOutputStream ouputStream) {
        try {
            if(inputFile.exists()) {
                /**如果是目录的话这里是不采取操作的,
                 * 至于目录的打包正在研究中*/
                if (inputFile.isFile()) {
                    FileInputStream IN = new FileInputStream(inputFile);
                    BufferedInputStream bins = new BufferedInputStream(IN, 512);
                    //org.apache.tools.zip.ZipEntry
                    String string = inputFile.getName().substring(17,inputFile.getName().length());
                    int lastIndexOf = string.lastIndexOf(".");
                    ZipEntry entry = new ZipEntry(string.substring(0, lastIndexOf-1)+a+string.substring(lastIndexOf,string.length()));
                    ouputStream.putNextEntry(entry);
                    // 向压缩文件中输出数据   
                    int nNumber;
                    byte[] buffer = new byte[512];
                    while ((nNumber = bins.read(buffer)) != -1) {
                        ouputStream.write(buffer, 0, nNumber);
                    }
                    // 关闭创建的流对象   
                    bins.close();
                    IN.close();
                } else {
                    try {
                        File[] files = inputFile.listFiles();
                        for (int i = 0; i < files.length; i++) {
                            zipFile(i,files[i], ouputStream);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值