Java上传下载实现

本例采用plupload+commons-fileupload包实现,源码下载地址:http://download.csdn.net/detail/lohocc/8104433

本文的代码跟提供的源码略有不同(根据项目需求后期进行加工改良),本文不介绍Http的断点续传(将在稍后的文章中进行介绍),这里只对主要代码做叙述

plupload下载地址:http://www.plupload.com/download/,这款插件可以支持多环境的多文件的上传(使用方便)

1.plupload在页面的配置

$("#uploader").pluploadQueue(
				$.extend({
					runtimes : runtime,//运行环境,html4,html5,flash等等,可配置多个,优先级为从前到后
					url : url,//后台处理上传的Action
					max_file_size : max_file_size,//文件大小限制
					//设置上传字段的名称,默认情况下被设置为文件(file)
					file_data_name : 'file',
					unique_names : true,
					multiple_queues : true,
					rename:true,
					filters : [ docFilter, imageFilter ],
					flash_swf_url : 'scripts/platform/common/upload/plupload/plupload.flash.swf',//flash上传页面路径
					init : {
						//文件上传成功的时候触发
						FileUploaded : function(uploader, file, response) {
							if (response.response) {
								files.push(file.name);
							}
						},
						//当队列中所有文件被上传完时触发
						UploadComplete : function(uploader, fs) {
							alert("上传完成!");
						},
						//上传出错的时候触发
						Error : function(l, o) {
							var m = o.file, n;
							if(m){
								n = o.message;
								if(o.details){
									n += " (" + o.details + ")";
								}
								if (o.code == plupload.FILE_SIZE_ERROR) {
									$.messager.alert('提示', m.name+'过大,上传限制:'+max_file_size+'m', 'info');
								}
								if (o.code == plupload.FILE_EXTENSION_ERROR) {
									alert("Error: Invalid file extension: "+ m.name);
								}
								m.hint = n;
								c("#" + m.id).attr("class","plupload_failed").find("a").css("display","block").attr("title", n);
								}
							}
						}
				}, (chunk ? {//当服务端大小限制时,分段上传
					chunk_size : '1mb'
				} : {})));
2.使用commons-fileupload处理上传请求

if (ServletFileUpload.isMultipartContent(request)) {
			try {
				DiskFileItemFactory factory = new DiskFileItemFactory();
				factory.setSizeThreshold(1024);
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setHeaderEncoding("UTF-8");
				upload.setSizeMax(Long.valueOf(uploadParams.get("allow-size")) * 1024 * 1024);// 设置上传大小
				List<FileItem> items = upload.parseRequest(request);
				//所有文件源信息列表
				List<FileUploadInfo> allFiles = new ArrayList<FileUploadInfo>();
				for (FileItem item : items) {
					if (!item.isFormField()) {// 如果是文件类型
						String itemUploadPath = checkSaveDir(request,
								item.getFieldName());
						name = item.getName();// 获得文件名
						String newName = UploadUtil.generatorUUIDName().concat(".").concat(
								FilenameUtils.getExtension(name));//随机生成一个不重复的文件名
						if (newName != null) {
							File savedFile = new File(itemUploadPath, newName);
							item.write(savedFile);//将上传文件写入磁盘
							//这里可以做一些自定义操作,如保留文件的详细信息到数据库等等
						}
					} else {//处理表单中其他信息,表单字段类型数据
						String itemName = item.getFieldName();
						String itemValue = item.getString(request.getCharacterEncoding());//这里防止出现乱码
						parameters.put(itemName, new String[] { itemValue });
					}
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
3.文件下载

文件下载的思路是单文件时直接下载,多文件则使用Zip流进行多文件打包下载

单文件下载:

public void downloadSingleFile(HttpServletResponse response,
			FileUploadInfo fileUploadInfo) {
		// 单文件下载,直接下载当前的文件
		String filePath = fileUploadInfo.getFilePath();
		String fileName = fileUploadInfo.getFileName();
		try {
			if (fileName != null && filePath != null) {
				OutputStream out = response.getOutputStream();
				File file = new File(filePath);
				response.setContentType("application/x-download");
				response.setContentLength((int)file.length());
				response.addHeader(
						"Content-Disposition",
						"attachment;filename="
								+ java.net.URLEncoder.encode(fileName, "UTF-8"));
				BufferedInputStream buff = new BufferedInputStream(
						new FileInputStream(file));
				byte[] b = new byte[1024];
				long k = 0;
				// 该值用于计算当前实际下载了多少字节
				// 开始循环下载
				while (k < file.length()) {
					int j = buff.read(b, 0, 1024);
					k += j;
					// 将写入到客户端的内存的数据,刷新到磁盘
					out.write(b, 0, j);
					out.flush();
				}
				buff.close();
				out.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
多文件下载(边压缩边下载):

public void downloadMultiFile(HttpServletResponse response,
			List<FileUploadInfo> fileUploadInfos) {
		ZipOutputStream zos = null;
		try {
			zos = new ZipOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			response.addHeader(
					"Content-Disposition",
					"attachment;filename="
							+ java.net.URLEncoder.encode(
									UploadUtil.getZipName(), "UTF-8"));
			UploadUtil.zipFiles(fileUploadInfos, zos);
			zos.flush();
			zos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
zipFiles方法
<pre name="code" class="java">public static void zipFiles(List<FileUploadInfo> infoVos, ZipOutputStream zos) throws IOException {       
	      for (FileUploadInfo info:infoVos) {
	       File f= new File(info.getFilePath());  
	       zos.putNextEntry(new ZipEntry(info.getFileName()));     
	       BufferedInputStream fis = new BufferedInputStream(new FileInputStream(f));
	       byte[] buffer = new byte[fis.available()];     
	       int r = 0;     
	       while ((r = fis.read(buffer)) != -1) {     
	           zos.write(buffer, 0, r);     
	       }     
	       fis.close();   
	      }  
	 }

这样一个文件上传下载的功能就搞定了




发布了42 篇原创文章 · 获赞 3 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章