use of org.apache.commons.fileupload.FileItem in project kie-wb-common by kiegroup.
the class FormsDocumentServlet method doPost.
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Map<String, Object> response = new HashMap<>();
try {
String id = UUID.randomUUID().toString();
FileItem fileItem = getFileItem(req);
File file = File.createTempFile(id, ".tmp");
file.deleteOnExit();
fileItem.write(file);
manager.uploadFile(id, file);
DocumentData data = new DocumentData(fileItem.getName(), fileItem.getSize(), null);
data.setContentId(id);
response.put("document", data);
} catch (Exception e) {
response.put("error", "error");
} finally {
writeResponse(resp, response);
}
}
use of org.apache.commons.fileupload.FileItem in project acs-community-packaging by Alfresco.
the class FileUploadBean method uploadFile.
/**
* Ajax method to upload file content. A multi-part form is required as the input.
*
* "return-page" = javascript to execute on return from the upload request
* "currentPath" = the cm:name based server path to upload the content into
* and the file item content.
*
* @throws Exception
*/
@InvokeCommand.ResponseMimetype(value = MimetypeMap.MIMETYPE_HTML)
public void uploadFile() throws Exception {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext externalContext = fc.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
upload.setHeaderEncoding("UTF-8");
List<FileItem> fileItems = upload.parseRequest(request);
FileUploadBean bean = new FileUploadBean();
String currentPath = null;
String filename = null;
String returnPage = null;
File file = null;
for (FileItem item : fileItems) {
if (item.isFormField() && item.getFieldName().equals("return-page")) {
returnPage = item.getString();
} else if (item.isFormField() && item.getFieldName().equals("currentPath")) {
currentPath = URLDecoder.decode(item.getString());
} else {
filename = FilenameUtils.getName(item.getName());
file = TempFileProvider.createTempFile("alfresco", ".upload");
item.write(file);
}
}
if (logger.isDebugEnabled())
logger.debug("Ajax file upload request: " + filename + " to path: " + currentPath + " return page: " + returnPage);
try {
if (file != null && currentPath != null && currentPath.length() != 0) {
NodeRef containerRef = pathToNodeRef(fc, currentPath);
if (containerRef != null) {
// Guess the mimetype
String mimetype = Repository.getMimeTypeForFileName(fc, filename);
// Now guess the encoding
String encoding = "UTF-8";
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(file));
encoding = Repository.guessEncoding(fc, is, mimetype);
} catch (Throwable e) {
// Bad as it is, it's not terminal
logger.error("Failed to guess character encoding of file: " + file, e);
} finally {
if (is != null) {
try {
is.close();
} catch (Throwable e) {
}
}
}
// Try and extract metadata from the file
ContentReader cr = new FileContentReader(file);
cr.setMimetype(mimetype);
// create properties for content type
String author = null;
String title = null;
String description = null;
Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>(5, 1.0f);
if (Repository.extractMetadata(fc, cr, contentProps)) {
author = (String) (contentProps.get(ContentModel.PROP_AUTHOR));
title = DefaultTypeConverter.INSTANCE.convert(String.class, contentProps.get(ContentModel.PROP_TITLE));
description = DefaultTypeConverter.INSTANCE.convert(String.class, contentProps.get(ContentModel.PROP_DESCRIPTION));
}
// default the title to the file name if not set
if (title == null) {
title = filename;
}
ServiceRegistry services = Repository.getServiceRegistry(fc);
FileInfo fileInfo = services.getFileFolderService().create(containerRef, filename, ContentModel.TYPE_CONTENT);
NodeRef fileNodeRef = fileInfo.getNodeRef();
// set the author aspect
if (author != null) {
Map<QName, Serializable> authorProps = new HashMap<QName, Serializable>(1, 1.0f);
authorProps.put(ContentModel.PROP_AUTHOR, author);
services.getNodeService().addAspect(fileNodeRef, ContentModel.ASPECT_AUTHOR, authorProps);
}
// apply the titled aspect - title and description
Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>(2, 1.0f);
titledProps.put(ContentModel.PROP_TITLE, title);
titledProps.put(ContentModel.PROP_DESCRIPTION, description);
services.getNodeService().addAspect(fileNodeRef, ContentModel.ASPECT_TITLED, titledProps);
// get a writer for the content and put the file
ContentWriter writer = services.getContentService().getWriter(fileNodeRef, ContentModel.PROP_CONTENT, true);
writer.setMimetype(mimetype);
writer.setEncoding(encoding);
writer.putContent(file);
}
}
} catch (Exception e) {
returnPage = returnPage.replace("${UPLOAD_ERROR}", e.getMessage());
} finally {
if (file != null) {
logger.debug("delete temporary file:" + file.getPath());
// Delete the temporary file
file.delete();
}
}
Document result = XMLUtil.newDocument();
Element htmlEl = result.createElement("html");
result.appendChild(htmlEl);
Element bodyEl = result.createElement("body");
htmlEl.appendChild(bodyEl);
Element scriptEl = result.createElement("script");
bodyEl.appendChild(scriptEl);
scriptEl.setAttribute("type", "text/javascript");
Node scriptText = result.createTextNode(returnPage);
scriptEl.appendChild(scriptText);
if (logger.isDebugEnabled()) {
logger.debug("File upload request complete.");
}
ResponseWriter out = fc.getResponseWriter();
XMLUtil.print(result, out);
}
use of org.apache.commons.fileupload.FileItem in project pentaho-platform by pentaho.
the class UploadFileServlet method doPost.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
IPentahoSession session = PentahoSessionHolder.getSession();
if (!hasManageDataAccessPermission(session)) {
response.sendError(403, Messages.getInstance().getErrorString("UploadFileServlet.ERROR_0009_UNAUTHORIZED"));
return;
}
UploadFileUtils utils = new UploadFileUtils(session);
// $NON-NLS-1$
response.setContentType("text/plain");
// Note - request.getParameter doesn't work on multi-part file data. But just in case,
// we get the standardRequestParamaters as well as the parameter map we create from the
// multi-part form data.
Map<String, String[]> standardRequestParameters = request.getParameterMap();
Map<String, FileItem> parsedMultiPartRequestParameters = this.getParsedRequestParameters(request, session);
// $NON-NLS-1$
FileItem uploadItem = parsedMultiPartRequestParameters.get("uploadFormElement");
if (uploadItem == null) {
// $NON-NLS-1$
String error = Messages.getInstance().getErrorString("UploadFileServlet.ERROR_0001_NO_FILE_TO_UPLOAD");
response.getWriter().write(error);
return;
}
// $NON-NLS-1$
String unzip = getRequestParameter(standardRequestParameters, parsedMultiPartRequestParameters, "unzip");
String temporary = // $NON-NLS-1$
getRequestParameter(standardRequestParameters, parsedMultiPartRequestParameters, "mark_temporary");
// $NON-NLS-1$
String fileName = getRequestParameter(standardRequestParameters, parsedMultiPartRequestParameters, "file_name");
if (StringUtils.isEmpty(fileName)) {
throw new ServletException(Messages.getInstance().getErrorString("UploadFileServlet.ERROR_0010_FILE_NAME_INVALID"));
}
boolean isTemporary = false;
if (temporary != null) {
isTemporary = Boolean.valueOf(temporary);
}
boolean shouldUnzip = false;
if (unzip != null) {
shouldUnzip = Boolean.valueOf(unzip);
}
utils.setShouldUnzip(shouldUnzip);
utils.setTemporary(isTemporary);
utils.setFileName(fileName);
utils.setWriter(response.getWriter());
utils.setUploadedFileItem(uploadItem);
// Do nothing with success value - the output should already have been written to the servlet response.
utils.process();
} catch (Exception e) {
String error = Messages.getInstance().getErrorString("UploadFileServlet.ERROR_0005_UNKNOWN_ERROR", // $NON-NLS-1
e.getLocalizedMessage());
response.getWriter().write(error);
}
}
use of org.apache.commons.fileupload.FileItem in project pentaho-platform by pentaho.
the class UploadFileServlet method getParsedRequestParameters.
/**
* Parses the multi-part request to get all the parameters out.
*
* @param request
* @param session
* @return Map of the request parameters
*/
private Map<String, FileItem> getParsedRequestParameters(HttpServletRequest request, IPentahoSession session) {
HashMap<String, FileItem> rtn = new HashMap<>();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> it = items.iterator();
while (it.hasNext()) {
FileItem item = it.next();
String fName = item.getFieldName();
rtn.put(fName, item);
}
} catch (FileUploadException e) {
return null;
}
return rtn;
}
use of org.apache.commons.fileupload.FileItem in project pentaho-platform by pentaho.
the class PluggableUploadFileServlet method getFileItem.
@SuppressWarnings("unchecked")
private FileItem getFileItem(HttpServletRequest request, long maxFileSize) throws FileUploadException {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(maxFileSize);
List items = upload.parseRequest(request);
Iterator it = items.iterator();
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
if (!item.isFormField()) {
return item;
}
}
return null;
}
Aggregations