此篇参考git代码:https://github.com/pdalcol/Zippex
学习salesforce可以访问一个朋友的网站:https://www.xgeek.net
首先感谢git上提供代码的大神,学到了新的知识。salesforce不像java提供生成Zip文件的类库,通过git上copy的代码可以实现此功能,具体的使用方法以及API可以查看上方git链接。
概述:实例模拟三个上传组件,加上一个下载Zip包按钮,本地选择需要上传的文件,点击按钮后便会下载成一个压缩文件,压缩文件中包含上传的文件内容。
一.ZipController:
1 public with sharing class ZipController { 2 3 public transient Blob fileUploadBody1{get;set;} 4 5 public String fileUploadName1{get;set;} 6 7 public transient Blob fileUploadBody2{get;set;} 8 9 public String fileUploadName2{get;set;} 10 11 public transient Blob fileUploadBody3{get;set;} 12 13 public String fileUploadName3{get;set;} 14 15 public transient Map<String,Blob> fileNameToBody{get;set;} 16 17 public PageReference reference{get;set;} 18 19 public PageReference downloadZip() { 20 String zipName = 'testZip.zip'; 21 String prefixFolder = 'folder/'; 22 fileNameToBody = new Map<String,Blob>(); 23 if(fileUploadName1 != null && fileUploadBody1 != null) { 24 fileNameToBody.put(fileUploadName1,fileUploadBody1); 25 } 26 if(fileUploadName2 != null && fileUploadBody2 != null) { 27 fileNameToBody.put(fileUploadName2,fileUploadBody2); 28 } 29 if(fileUploadName3 != null && fileUploadBody3 != null) { 30 fileNameToBody.put(fileUploadName3,fileUploadBody3); 31 } 32 Zippex zip = new Zippex(); 33 for(String fileName : fileNameToBody.keySet()) { 34 zip.addFile(prefixFolder + fileName, fileNameToBody.get(fileName),null); 35 } 36 try{ 37 Document doc = new Document(); 38 doc.FolderId = UserInfo.getUserId(); 39 doc.Name = zipName; 40 doc.Body = zip.getZipArchive(); 41 insert doc; 42 return new PageReference('/servlet/servlet.FileDownload?file=' + doc.Id); 43 } catch ( Exception ex ) { 44 ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'生成zip失败')); 45 } 46 return null; 47 } 48 }
二.ZipPage
<apex:page controller="ZipController"> <apex:form > <apex:pageMessages /> <apex:inputFile value="{!fileUploadBody1}" filename="{!fileUploadName1}" /> <apex:inputFile value="{!fileUploadBody2}" filename="{!fileUploadName2}" /> <apex:inputFile value="{!fileUploadBody3}" filename="{!fileUploadName3}" /> <apex:pageBlock title="download zip "> <apex:commandButton action="{!downloadZip}" value="Download"/> </apex:pageBlock> </apex:form> </apex:page>
三.显示效果:
总结:此种方式对于中文文件处理会有乱码问题,本来想通过addFile方法进行一下UTF-8编码转换,结果转换完getZipArchive方法出现了编码解码的异常,有兴趣的朋友可以解决中文乱码的问题并且欢迎分享。