此篇参考git代码:https://github.com/pdalcol/Zippex
学习salesforce可以访问一个朋友的网站:https://www.xgeek.net
首先感谢git上提供代码的大神,学到了新的知识。salesforce不像java提供生成Zip文件的类库,通过git上copy的代码可以实现此功能,具体的使用方法以及API可以查看上方git链接。
概述:实例模拟三个上传组件,加上一个下载Zip包按钮,本地选择需要上传的文件,点击按钮后便会下载成一个压缩文件,压缩文件中包含上传的文件内容。
一.ZipController:
public with sharing class ZipController { public transient Blob fileUploadBody1{get;set;} public String fileUploadName1{get;set;} public transient Blob fileUploadBody2{get;set;} public String fileUploadName2{get;set;} public transient Blob fileUploadBody3{get;set;} public String fileUploadName3{get;set;} public transient Map<String,Blob> fileNameToBody{get;set;} public PageReference reference{get;set;} public PageReference downloadZip() {
String zipName = 'testZip.zip';
String prefixFolder = 'folder/';
fileNameToBody = new Map<String,Blob>();
if(fileUploadName1 != null && fileUploadBody1 != null) {
fileNameToBody.put(fileUploadName1,fileUploadBody1);
}
if(fileUploadName2 != null && fileUploadBody2 != null) {
fileNameToBody.put(fileUploadName2,fileUploadBody2);
}
if(fileUploadName3 != null && fileUploadBody3 != null) {
fileNameToBody.put(fileUploadName3,fileUploadBody3);
}
Zippex zip = new Zippex();
for(String fileName : fileNameToBody.keySet()) {
zip.addFile(prefixFolder + fileName, fileNameToBody.get(fileName),null);
}
try{
Document doc = new Document();
doc.FolderId = UserInfo.getUserId();
doc.Name = zipName;
doc.Body = zip.getZipArchive();
insert doc;
return new PageReference('/servlet/servlet.FileDownload?file=' + doc.Id);
} catch ( Exception ex ) {
ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'生成zip失败'));
}
return null;
}
}
二.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方法出现了编码解码的异常,有兴趣的朋友可以解决中文乱码的问题并且欢迎分享。