use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project v7files by thiloplanz.
the class BucketsServlet method doFormPost.
private void doFormPost(HttpServletRequest request, HttpServletResponse response, BSONObject bucket) throws IOException {
ObjectId uploadId = new ObjectId();
BSONObject parameters = new BasicBSONObject();
List<FileItem> files = new ArrayList<FileItem>();
if (ServletFileUpload.isMultipartContent(request)) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
for (Object _file : upload.parseRequest(request)) {
FileItem file = (FileItem) _file;
if (file.isFormField()) {
String v = file.getString();
parameters.put(file.getFieldName(), v);
} else {
files.add(file);
}
}
} catch (FileUploadException e) {
throw new IOException(e);
}
} else {
for (Entry<String, String[]> param : request.getParameterMap().entrySet()) {
String[] v = param.getValue();
if (v.length == 1)
parameters.put(param.getKey(), v[0]);
else
parameters.put(param.getKey(), v);
}
}
BSONObject result = new BasicBSONObject("_id", uploadId);
BSONObject uploads = new BasicBSONObject();
for (FileItem file : files) {
DiskFileItem f = (DiskFileItem) file;
// inline until 10KB
if (f.isInMemory()) {
uploads.put(f.getFieldName(), storage.inlineOrInsertContentsAndBackRefs(10240, f.get(), uploadId, f.getName(), f.getContentType()));
} else {
uploads.put(f.getFieldName(), storage.inlineOrInsertContentsAndBackRefs(10240, f.getStoreLocation(), uploadId, f.getName(), f.getContentType()));
}
file.delete();
}
result.put("files", uploads);
result.put("parameters", parameters);
bucketCollection.update(new BasicDBObject("_id", bucket.get("_id")), new BasicDBObject("$push", new BasicDBObject("FormPost.data", result)));
String redirect = BSONUtils.getString(bucket, "FormPost.redirect");
// redirect mode
if (StringUtils.isNotBlank(redirect)) {
response.sendRedirect(redirect + "?v7_formpost_id=" + uploadId);
return;
}
// echo mode
// JSON does not work, see https://jira.mongodb.org/browse/JAVA-332
// response.setContentType("application/json");
// response.getWriter().write(JSON.serialize(result));
byte[] bson = BSON.encode(result);
response.getOutputStream().write(bson);
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project ghostdriver by detro.
the class FileUploadTest method checkMultipleFileUploadCompletes.
@Test
public void checkMultipleFileUploadCompletes() throws IOException {
WebDriver d = getDriver();
// Create the test file for uploading
File testFile = File.createTempFile("webdriver", "tmp");
testFile.deleteOnExit();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(testFile.getAbsolutePath()), "utf-8"));
writer.write(FILE_HTML);
writer.close();
// Create the test file for uploading
File testFile2 = File.createTempFile("webdriver", "tmp");
testFile2.deleteOnExit();
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(testFile2.getAbsolutePath()), "utf-8"));
writer.write(FILE_HTML2);
writer.close();
server.setHttpHandler("POST", new HttpRequestCallback() {
@Override
public void call(HttpServletRequest req, HttpServletResponse res) throws IOException {
if (ServletFileUpload.isMultipartContent(req) && req.getPathInfo().endsWith("/uploadmult")) {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory(1024, new File(System.getProperty("java.io.tmpdir")));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List<FileItem> items;
try {
items = upload.parseRequest(req);
} catch (FileUploadException fue) {
throw new IOException(fue);
}
res.setHeader("Content-Type", "text/html; charset=UTF-8");
InputStream is = items.get(0).getInputStream();
OutputStream os = res.getOutputStream();
IOUtils.copy(is, os);
is = items.get(1).getInputStream();
IOUtils.copy(is, os);
os.write("<script>window.top.window.onUploadDone();</script>".getBytes());
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
return;
}
res.sendError(400);
}
});
// Upload the temp file
d.get(server.getBaseUrl() + "/common/upload-multiple.html");
d.findElement(By.id("upload")).sendKeys(testFile.getAbsolutePath() + "\n" + testFile2.getAbsolutePath());
d.findElement(By.id("go")).submit();
// Uploading files across a network may take a while, even if they're really small.
// Wait for the loading label to disappear.
WebDriverWait wait = new WebDriverWait(d, 10);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("upload_label")));
d.switchTo().frame("upload_target");
wait = new WebDriverWait(d, 5);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//body"), LOREM_IPSUM_TEXT));
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//body"), "Hello"));
// Navigate after file upload to verify callbacks are properly released.
d.get("http://www.google.com/");
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project jaggery by wso2.
the class RequestHostObject method parseMultipart.
private static void parseMultipart(RequestHostObject rho) throws ScriptException {
if (rho.files != null) {
return;
}
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(rho.request);
} catch (FileUploadException e) {
log.error(e.getMessage(), e);
throw new ScriptException(e);
}
// Process the uploaded items
String name;
rho.files = rho.context.newObject(rho);
for (Object obj : items) {
FileItem item = (FileItem) obj;
name = item.getFieldName();
if (item.isFormField()) {
ArrayList<FileItem> x = (ArrayList<FileItem>) rho.parameterMap.get(name);
if (x == null) {
ArrayList<FileItem> array = new ArrayList<FileItem>(1);
array.add(item);
rho.parameterMap.put(name, array);
} else {
x.add(item);
}
} else {
rho.files.put(item.getFieldName(), rho.files, rho.context.newObject(rho, "File", new Object[] { item }));
}
}
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project tomee by apache.
the class CommonsFileUploadPartFactory method read.
public static Collection<Part> read(final HttpRequestImpl request) {
// mainly for testing
// Create a new file upload handler
final DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(REPO);
final ServletFileUpload upload = new ServletFileUpload();
upload.setFileItemFactory(factory);
final List<Part> parts = new ArrayList<>();
try {
final List<FileItem> items = upload.parseRequest(new ServletRequestContext(request));
final String enc = request.getCharacterEncoding();
for (final FileItem item : items) {
final CommonsFileUploadPart part = new CommonsFileUploadPart(item, null);
parts.add(part);
if (part.getSubmittedFileName() == null) {
String name = part.getName();
String value = null;
try {
String encoding = request.getCharacterEncoding();
if (encoding == null) {
if (enc == null) {
encoding = "UTF-8";
} else {
encoding = enc;
}
}
value = part.getString(encoding);
} catch (final UnsupportedEncodingException uee) {
try {
value = part.getString("UTF-8");
} catch (final UnsupportedEncodingException e) {
// not possible
}
}
request.addInternalParameter(name, value);
}
}
return parts;
} catch (final FileUploadException e) {
throw new IllegalStateException(e);
}
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project MSEC by Tencent.
the class FileUploadTool method FileUpload.
public static String FileUpload(Map<String, String> fields, List<String> filesOnServer, HttpServletRequest request, HttpServletResponse response) {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
DiskFileItemFactory factory = new DiskFileItemFactory();
int MaxMemorySize = 10000000;
int MaxRequestSize = MaxMemorySize;
String tmpDir = System.getProperty("TMP", "/tmp");
System.out.printf("temporary directory:%s", tmpDir);
factory.setSizeThreshold(MaxMemorySize);
factory.setRepository(new File(tmpDir));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(MaxRequestSize);
// Parse the request
try {
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();
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();
}
}
Aggregations