У меня есть форма с двумя полями форматированного текста, используемыми для хранения вложений, и XPage, который содержит два элемента управления загрузкой файлов (по одному для каждого поля) и две кнопки.
Кнопки вызывают метод в классе Java, который создает zip-файл, содержащий файлы из соответствующего поля. Зип-файл скачивается в браузере для пользователя.
Все работает отлично – не считая того, что если скачать один zip-файл, то сразу скачать другой нельзя. Прежде чем второе нажатие кнопки что-либо даст, происходит задержка около 15–20 секунд.
XPage: -
Код: Выделить всё
Код: Выделить всё
package uk.co.mp;
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
import lotus.domino.Document;
import lotus.domino.EmbeddedObject;
import lotus.domino.RichTextItem;
import com.ibm.xsp.designer.context.XSPContext;
import com.ibm.xsp.model.domino.DominoUtils;
//
import lotus.domino.Session;
import lotus.domino.Database;
import com.ibm.xsp.extlib.util.ExtLibUtil;
public class DownloadAllAttachments {
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void downloadFromField(String documentUNID, String fieldName) {
// Initialize global XPage objects
FacesContext facesContext = FacesContext.getCurrentInstance();
XSPContext context = XSPContext.getXSPContext(facesContext);
UIViewRoot view = facesContext.getViewRoot();
Map viewScope = view.getViewMap();
try {
if (documentUNID == null || documentUNID.trim().equals("")) {
viewScope.put("errorString", "URL parameter \"documentUNID\" or \"u\" is required.");
view.setRendered(true);
return;
}
Session s = ExtLibUtil.getCurrentSessionAsSigner();
Database db = s.getCurrentDatabase();
// Get and validate the document from which attachments would be zipped
Document downloadDocument = null;
downloadDocument = db.getDocumentByUNID(documentUNID);
// Get and validate zip file name from URL
String zipFileName = fieldName + ".zip";
boolean bAnyAttachments = false;
EmbeddedObject embeddedObj = null;
Vector attachments = null;
// ...check for attachments in the field supplied and collect the names of the attachments
RichTextItem rtitem = (RichTextItem)downloadDocument.getFirstItem(fieldName);
Vector vec = rtitem.getEmbeddedObjects();
attachments = new Vector(vec.size());
if (!vec.isEmpty()) {
Iterator it = vec.iterator();
while(it.hasNext()){
embeddedObj = (EmbeddedObject)it.next();
if (embeddedObj != null) {
attachments.add(embeddedObj.getName());
bAnyAttachments = true;
}
}
}
//By this point we should have a list of the attachment names we want to include in the zip file
//If we have not found any attachments then return a message
if (!bAnyAttachments) {
viewScope.put("errorString", "No attachments found in the Document.");
return;
}
// Set response header values
HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", -1);
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=" + zipFileName);
// Get stream related objects
OutputStream outStream = response.getOutputStream();
ZipOutputStream zipOutStream = new ZipOutputStream(outStream);
BufferedInputStream bufferInStream = null;
// Get all attachment names and loop through all of them adding to zip
for (int i = 0; i < attachments.size(); i++) {
embeddedObj = downloadDocument.getAttachment(attachments.get(i).toString());
if (embeddedObj != null) {
bufferInStream = new BufferedInputStream(embeddedObj.getInputStream());
int bufferLength = bufferInStream.available();
byte data[] = new byte[bufferLength];
bufferInStream.read(data, 0, bufferLength); // Read the attachment data
ZipEntry entry = new ZipEntry(embeddedObj.getName());
zipOutStream.putNextEntry(entry);
zipOutStream.write(data); // Write attachment into Zip file
bufferInStream.close();
embeddedObj.recycle();
}
}
// Clean up and close objects
downloadDocument.recycle();
zipOutStream.flush();
zipOutStream.close();
outStream.flush();
outStream.close();
facesContext.responseComplete();
} catch (Exception e) {
viewScope.put("errorString", "Error while zipping attachments.
" + e.toString());
e.printStackTrace();
}
}
}
Источник: https://stackoverflow.com/questions/781 ... akes-place