use of org.apache.commons.fileupload.FileItem in project acs-community-packaging by Alfresco.
the class UploadFileServlet method service.
/**
* @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uploadId = null;
String returnPage = null;
final RequestContext requestContext = new ServletRequestContext(request);
boolean isMultipart = ServletFileUpload.isMultipartContent(requestContext);
try {
AuthenticationStatus status = servletAuthenticate(request, response);
if (status == AuthenticationStatus.Failure) {
return;
}
if (!isMultipart) {
throw new AlfrescoRuntimeException("This servlet can only be used to handle file upload requests, make" + "sure you have set the enctype attribute on your form to multipart/form-data");
}
if (logger.isDebugEnabled())
logger.debug("Uploading servlet servicing...");
FacesContext context = FacesContext.getCurrentInstance();
Map<Object, Object> session = context.getExternalContext().getSessionMap();
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
// ensure that the encoding is handled correctly
upload.setHeaderEncoding("UTF-8");
List<FileItem> fileItems = upload.parseRequest(request);
FileUploadBean bean = new FileUploadBean();
for (FileItem item : fileItems) {
if (item.isFormField()) {
if (item.getFieldName().equalsIgnoreCase("return-page")) {
returnPage = item.getString();
} else if (item.getFieldName().equalsIgnoreCase("upload-id")) {
uploadId = item.getString();
}
} else {
String filename = item.getName();
if (filename != null && filename.length() != 0) {
if (logger.isDebugEnabled()) {
logger.debug("Processing uploaded file: " + filename);
}
// ADB-41: Ignore non-existent files i.e. 0 byte streams.
if (allowZeroByteFiles() == true || item.getSize() > 0) {
// workaround a bug in IE where the full path is returned
// IE is only available for Windows so only check for the Windows path separator
filename = FilenameUtils.getName(filename);
final File tempFile = TempFileProvider.createTempFile("alfresco", ".upload");
item.write(tempFile);
bean.setFile(tempFile);
bean.setFileName(filename);
bean.setFilePath(tempFile.getAbsolutePath());
if (logger.isDebugEnabled()) {
logger.debug("Temp file: " + tempFile.getAbsolutePath() + " size " + tempFile.length() + " bytes created from upload filename: " + filename);
}
} else {
if (logger.isWarnEnabled())
logger.warn("Ignored file '" + filename + "' as there was no content, this is either " + "caused by uploading an empty file or a file path that does not exist on the client.");
}
}
}
}
session.put(FileUploadBean.getKey(uploadId), bean);
if (bean.getFile() == null && uploadId != null && logger.isWarnEnabled()) {
logger.warn("no file uploaded for upload id: " + uploadId);
}
if (returnPage == null || returnPage.length() == 0) {
throw new AlfrescoRuntimeException("return-page parameter has not been supplied");
}
JSONObject json;
try {
json = new JSONObject(returnPage);
if (json.has("id") && json.has("args")) {
// finally redirect
if (logger.isDebugEnabled()) {
logger.debug("Sending back javascript response " + returnPage);
}
response.setContentType(MimetypeMap.MIMETYPE_HTML);
response.setCharacterEncoding("utf-8");
// work-around for WebKit protection against embedded javascript on POST body response
response.setHeader("X-XSS-Protection", "0");
final PrintWriter out = response.getWriter();
out.println("<html><body><script type=\"text/javascript\">");
out.println("window.parent.upload_complete_helper(");
out.println("'" + json.getString("id") + "'");
out.println(", ");
out.println(json.getJSONObject("args"));
out.println(");");
out.println("</script></body></html>");
out.close();
}
} catch (JSONException e) {
// finally redirect
if (logger.isDebugEnabled())
logger.debug("redirecting to: " + returnPage);
response.sendRedirect(returnPage);
}
if (logger.isDebugEnabled())
logger.debug("upload complete");
} catch (Throwable error) {
handleUploadException(request, response, error, returnPage);
}
}
use of org.apache.commons.fileupload.FileItem in project JessMA by ldcsaa.
the class FileUploader method upload.
/**
* 执行上传
*
* @param request : {@link HttpServletRequest} 对象
* @param response : {@link HttpServletResponse} 对象
*
* @return : 成功:返回 {@link Result#SUCCESS} ,失败:返回其他结果,
* 失败原因通过 {@link FileUploader#getCause()} 获取
*/
public Result upload(HttpServletRequest request, HttpServletResponse response) {
reset();
String absolutePath = getAbsoluteSavePath(request);
if (absolutePath == null) {
cause = new FileNotFoundException(String.format("path '%s' not found or is not directory", savePath));
return Result.INVALID_SAVE_PATH;
}
ServletFileUpload sfu = getFileUploadComponent();
List<FileItemInfo> fiis = new ArrayList<FileItemInfo>();
List<FileItem> items = null;
Result result = Result.SUCCESS;
String encoding = servletHeaderencoding != null ? servletHeaderencoding : request.getCharacterEncoding();
FileNameGenerator fnGenerator = fileNameGenerator != null ? fileNameGenerator : DEFAULT_FILE_NAME_GENERATOR;
try {
items = (List<FileItem>) sfu.parseRequest(request);
} catch (FileUploadException e) {
cause = e;
if (e instanceof FileSizeLimitExceededException)
result = Result.FILE_SIZE_EXCEEDED;
else if (e instanceof SizeLimitExceededException)
result = Result.SIZE_EXCEEDED;
else if (e instanceof InvalidContentTypeException)
result = Result.INVALID_CONTENT_TYPE;
else if (e instanceof IOFileUploadException)
result = Result.FILE_UPLOAD_IO_EXCEPTION;
else
result = Result.OTHER_PARSE_REQUEST_EXCEPTION;
}
if (result == Result.SUCCESS) {
result = parseFileItems(items, fnGenerator, absolutePath, encoding, fiis);
if (result == Result.SUCCESS)
result = writeFiles(fiis);
}
return result;
}
use of org.apache.commons.fileupload.FileItem in project xwiki-platform by xwiki.
the class FileUploadPlugin method cleanFileList.
/**
* Deletes all temporary files of the upload.
*
* @param context Context of the request.
* @see FileUploadPluginApi#cleanFileList()
*/
public void cleanFileList(XWikiContext context) {
LOGGER.debug("Cleaning uploaded files");
List<FileItem> fileuploadlist = getFileItems(context);
if (fileuploadlist != null) {
for (FileItem item : fileuploadlist) {
try {
item.delete();
} catch (Exception ex) {
LOGGER.warn("Exception cleaning uploaded files", ex);
}
}
context.remove(FILE_LIST_KEY);
}
}
use of org.apache.commons.fileupload.FileItem in project xwiki-platform by xwiki.
the class FileUploadPlugin method getFileItemNames.
/**
* Retrieves the list of FileItem names. {@link #loadFileList(XWikiContext)} needs to be called beforehand.
*
* @param context Context of the request
* @return List of strings of the item names
*/
public List<String> getFileItemNames(XWikiContext context) {
List<String> itemnames = new ArrayList<String>();
List<FileItem> fileuploadlist = getFileItems(context);
if (fileuploadlist == null) {
return itemnames;
}
for (FileItem item : fileuploadlist) {
itemnames.add(item.getFieldName());
}
return itemnames;
}
use of org.apache.commons.fileupload.FileItem in project xwiki-platform by xwiki.
the class FileUploadPlugin method getFile.
/**
* Return the FileItem corresponding to the file uploaded for a form field.
*
* @param formfieldName The name of the form field.
* @param context Context of the request.
* @return The corresponding FileItem, or <tt>null</tt> if no file was uploaded for that form field.
*/
public FileItem getFile(String formfieldName, XWikiContext context) {
LOGGER.debug("Searching file uploaded for field " + formfieldName);
List<FileItem> fileuploadlist = getFileItems(context);
if (fileuploadlist == null) {
return null;
}
FileItem fileitem = null;
for (FileItem item : fileuploadlist) {
if (formfieldName.equals(item.getFieldName())) {
fileitem = item;
LOGGER.debug("Found uploaded file!");
break;
}
}
return fileitem;
}
Aggregations