j2ee 上传下载 小记
上传:
文件上传,通常是使用form表单提交,关键是设置enctype="multipart/form-data",然后submit就行了。
<form name="fileForm" id="fileForm" action="${ctx }/resource/resUpload.do" enctype="multipart/form-data" method="post">
<input id="file_url1" name="file_url1" type="file" />
</form>
至于后台java端的处理,有很多方式,这里提供一个springmvc处理文件上传方法:http://blog.csdn.net/a1314517love/article/details/24183273
使用form表单提交,会发生页面跳转。这是让人有点小不爽的。
下面介绍一种方法,使用ajax动态上传文件,页面不会跳转。
使用jquery-form.js组件,页面中先引入jquery.js,然后引入jquery-form.js,顺序不能错(用过jQuery的应该都知道)。
1 function fileFormSubmit(){ 2 var ajax_option={ 3 target : '#output', 4 beforeSubmit : function(){// 提交前的调用的方法 5 6 }, 7 success : function(formData, jqForm, options){// 提交后的回调函数 8 9 }, 10 // url : url, 11 type : 'POST', 12 dataType : "json", 13 // clearForm : true, 14 resetForm : true, 15 timeout : 3000 16 }; 17 // 提交form表单 18 $("#fileForm").ajaxSubmit(ajax_option); 19 }
详细的解释,可以参考一下http://www.cnblogs.com/sydeveloper/p/3754637.html
下载:
下载功能主要是java端编程。
首先这是response的一些属性
1 //设置文件ContentType类型,这样设置,会自动判断下载文件类型 2 response.setContentType("multipart/form-data"); 3 String filename = ""; 4 //防止中文名称乱码,将名称转成ISO8859-1编码 5 response.setHeader("Content-Disposition", "attachment;fileName="+new String(filename.toString().getBytes("utf-8"),"ISO8859-1"));
单个文件,处理文件流,直接下载
//要下载的文件的路径 String downfilePath = ""; ServletOutputStream out; //通过文件路径获得File对象 File file = new File(downfilePath); try { FileInputStream inputStream = new FileInputStream(file); //3.通过response获取ServletOutputStream对象(out) out = response.getOutputStream(); int b = 0; byte[] buffer = new byte[1024]; while ((b = inputStream.read(buffer)) > -1){ out.write(buffer,0,b); //4.写到输出流(out)中 } inputStream.close(); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); }
多个文件,压缩成zip文件,再下载
//zip文件生成的路径,例如c:\\zipfile\\ceshi123.zip String destPath = ""; ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(destPath))); for(String p: paths){ File file = new File(p); //压缩文件,将文件放入zos中 compressFile(file, zos, ""); } //关闭流,不然会出问题 zos.close();
private static void compressFile(File file, ZipOutputStream zos, String dir) throws Exception { /** * 压缩包内文件名定义 * * <pre> * 如果有多级目录,那么这里就需要给出包含目录的文件名 * 如果用WinRAR打开压缩包,中文名将显示为乱码 * </pre> */ ZipEntry entry = new ZipEntry(dir + file.getName()); zos.putNextEntry(entry); BufferedInputStream bis = new BufferedInputStream(new FileInputStream( file)); int count; byte data[] = new byte[1024]; while ((count = bis.read(data, 0, 1024)) != -1) { zos.write(data, 0, count); } bis.close(); zos.closeEntry(); }
这样就会在destPath 对应的目录中生成一个zip文件了,然后单个文件,处理文件流,直接下载。
浙公网安备 33010602011771号