use of org.apache.commons.fileupload.servlet.ServletFileUpload in project libresonic by Libresonic.
the class ImportPlaylistController method handlePost.
@RequestMapping(method = RequestMethod.POST)
protected String handlePost(RedirectAttributes redirectAttributes, HttpServletRequest request) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
try {
if (ServletFileUpload.isMultipartContent(request)) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<?> items = upload.parseRequest(request);
for (Object o : items) {
FileItem item = (FileItem) o;
if ("file".equals(item.getFieldName()) && !StringUtils.isBlank(item.getName())) {
if (item.getSize() > MAX_PLAYLIST_SIZE_MB * 1024L * 1024L) {
throw new Exception("The playlist file is too large. Max file size is " + MAX_PLAYLIST_SIZE_MB + " MB.");
}
String playlistName = FilenameUtils.getBaseName(item.getName());
String fileName = FilenameUtils.getName(item.getName());
String format = StringUtils.lowerCase(FilenameUtils.getExtension(item.getName()));
String username = securityService.getCurrentUsername(request);
Playlist playlist = playlistService.importPlaylist(username, playlistName, fileName, format, item.getInputStream(), null);
map.put("playlist", playlist);
}
}
}
} catch (Exception e) {
map.put("error", e.getMessage());
}
redirectAttributes.addFlashAttribute("model", map);
return "redirect:importPlaylist";
}
use of org.apache.commons.fileupload.servlet.ServletFileUpload in project pratilipi by Pratilipi.
the class GenericApi method executeApi.
final Object executeApi(GenericApi api, Method apiMethod, JsonObject requestPayloadJson, Class<? extends GenericRequest> apiMethodParameterType, HttpServletRequest request) {
try {
GenericRequest apiRequest = new Gson().fromJson(requestPayloadJson, apiMethodParameterType);
if (apiRequest instanceof GenericFileUploadRequest) {
GenericFileUploadRequest gfuRequest = (GenericFileUploadRequest) apiRequest;
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(request);
while (iterator.hasNext()) {
FileItemStream fileItemStream = iterator.next();
if (!fileItemStream.isFormField()) {
gfuRequest.setName(fileItemStream.getName());
gfuRequest.setData(IOUtils.toByteArray(fileItemStream.openStream()));
gfuRequest.setMimeType(fileItemStream.getContentType());
break;
}
}
} catch (IOException | FileUploadException e) {
throw new UnexpectedServerException();
}
}
JsonObject errorMessages = apiRequest.validate();
if (errorMessages.entrySet().size() > 0)
return new InvalidArgumentException(errorMessages);
else
return apiMethod.invoke(api, apiRequest);
} catch (JsonSyntaxException e) {
logger.log(Level.SEVERE, "Invalid JSON in request body.", e);
return new InvalidArgumentException("Invalid JSON in request body.");
} catch (UnexpectedServerException e) {
return e;
} catch (InvocationTargetException e) {
Throwable te = e.getTargetException();
if (te instanceof InvalidArgumentException || te instanceof InsufficientAccessException || te instanceof UnexpectedServerException) {
return te;
} else {
logger.log(Level.SEVERE, "Failed to execute API.", te);
return new UnexpectedServerException();
}
} catch (IllegalAccessException | IllegalArgumentException e) {
logger.log(Level.SEVERE, "Failed to execute API.", e);
return new UnexpectedServerException();
}
}
use of org.apache.commons.fileupload.servlet.ServletFileUpload in project MSEC by Tencent.
the class FileUploadServlet method FileUpload.
//处理multi-part格式的http请求
//将key-value字段放到fields里返回
//将文件保存到tmp目录,并将文件名保存到filesOnServer列表里返回
protected static String FileUpload(Map<String, String> fields, List<String> filesOnServer, HttpServletRequest request, HttpServletResponse response) {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
int MaxMemorySize = 10000000;
int MaxRequestSize = MaxMemorySize;
String tmpDir = System.getProperty("TMP", "/tmp");
//System.out.printf("temporary directory:%s", tmpDir);
// Set factory constraints
factory.setSizeThreshold(MaxMemorySize);
factory.setRepository(new File(tmpDir));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf8");
// Set overall request size constraint
upload.setSizeMax(MaxRequestSize);
// Parse the request
try {
@SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request);
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField()) {
//普通的k -v字段
String name = item.getFieldName();
String value = item.getString("utf-8");
fields.put(name, value);
} else {
String fieldName = item.getFieldName();
String fileName = item.getName();
if (fileName == null || fileName.length() < 1) {
return "file name is empty.";
}
String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator + fileName;
//System.out.printf("upload file:%s", localFileName);
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
File uploadedFile = new File(localFileName);
item.write(uploadedFile);
filesOnServer.add(localFileName);
}
}
return "success";
} catch (FileUploadException e) {
e.printStackTrace();
return e.toString();
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
use of org.apache.commons.fileupload.servlet.ServletFileUpload in project zm-mailbox by Zimbra.
the class FileUploadServlet method handleMultipartUpload.
@SuppressWarnings("unchecked")
List<Upload> handleMultipartUpload(HttpServletRequest req, HttpServletResponse resp, String fmt, Account acct, boolean limitByFileUploadMaxSize, AuthToken at, boolean csrfCheckComplete) throws IOException, ServiceException {
List<FileItem> items = null;
String reqId = null;
ServletFileUpload upload = getUploader2(limitByFileUploadMaxSize);
try {
items = upload.parseRequest(req);
if (!csrfCheckComplete && !CsrfUtil.checkCsrfInMultipartFileUpload(items, at)) {
drainRequestStream(req);
mLog.info("CSRF token validation failed for account: %s, Auth token is CSRF enabled", acct.getName());
sendResponse(resp, HttpServletResponse.SC_UNAUTHORIZED, fmt, null, null, items);
return Collections.emptyList();
}
} catch (FileUploadBase.SizeLimitExceededException e) {
// at least one file was over max allowed size
mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes: " + e);
drainRequestStream(req);
sendResponse(resp, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, fmt, reqId, null, items);
return Collections.emptyList();
} catch (FileUploadBase.InvalidContentTypeException e) {
// at least one file was of a type not allowed
mLog.info("File upload failed", e);
drainRequestStream(req);
sendResponse(resp, HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, fmt, reqId, null, items);
return Collections.emptyList();
} catch (FileUploadException e) {
// parse of request failed for some other reason
mLog.info("File upload failed", e);
drainRequestStream(req);
sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fmt, reqId, null, items);
return Collections.emptyList();
}
String charset = "utf-8";
LinkedList<String> names = new LinkedList<String>();
HashMap<FileItem, String> filenames = new HashMap<FileItem, String>();
if (items != null) {
for (Iterator<FileItem> it = items.iterator(); it.hasNext(); ) {
FileItem fi = it.next();
if (fi == null)
continue;
if (fi.isFormField()) {
if (fi.getFieldName().equals("requestId")) {
// correlate this file upload session's request and response
reqId = fi.getString();
} else if (fi.getFieldName().equals("_charset_") && !fi.getString().equals("")) {
// get the form value charset, if specified
charset = fi.getString();
} else if (fi.getFieldName().startsWith("filename")) {
// allow a client to explicitly provide filenames for the uploads
names.clear();
String value = fi.getString(charset);
if (!Strings.isNullOrEmpty(value)) {
for (String name : value.split("\n")) {
names.add(name.trim());
}
}
}
// strip form fields out of the list of uploads
it.remove();
} else {
if (fi.getName() == null || fi.getName().trim().equals("")) {
it.remove();
} else {
filenames.put(fi, names.isEmpty() ? null : names.remove());
}
}
}
}
// restrict requestId value for safety due to later use in javascript
if (reqId != null && reqId.length() != 0) {
if (!ALLOWED_REQUESTID_CHARS.matcher(reqId).matches()) {
mLog.info("Rejecting upload with invalid chars in reqId: %s", reqId);
sendResponse(resp, HttpServletResponse.SC_BAD_REQUEST, fmt, null, null, items);
return Collections.emptyList();
}
}
// empty upload is not a "success"
if (items == null || items.isEmpty()) {
mLog.info("No data in upload for reqId: %s", reqId);
sendResponse(resp, HttpServletResponse.SC_NO_CONTENT, fmt, reqId, null, items);
return Collections.emptyList();
}
// cache the uploaded files in the hash and construct the list of upload IDs
List<Upload> uploads = new ArrayList<Upload>(items.size());
for (FileItem fi : items) {
String name = filenames.get(fi);
if (name == null || name.trim().equals(""))
name = fi.getName();
Upload up = new Upload(acct.getId(), fi, name);
mLog.info("Received multipart: %s", up);
synchronized (mPending) {
mPending.put(up.uuid, up);
}
uploads.add(up);
}
sendResponse(resp, HttpServletResponse.SC_OK, fmt, reqId, uploads, items);
return uploads;
}
use of org.apache.commons.fileupload.servlet.ServletFileUpload in project zm-mailbox by Zimbra.
the class FileUploadServlet method getUploader.
public static ServletFileUpload getUploader(long maxSize) {
DiskFileItemFactory dfif = new DiskFileItemFactory();
dfif.setSizeThreshold(32 * 1024);
dfif.setRepository(new File(getUploadDir()));
ServletFileUpload upload = new ServletFileUpload(dfif);
upload.setSizeMax(maxSize);
upload.setHeaderEncoding("utf-8");
return upload;
}
Aggregations