use of org.apache.commons.fileupload.disk.DiskFileItem in project OpenClinica by OpenClinica.
the class XformMetaDataService method getMediaFileItemFromFormManager.
public FileItem getMediaFileItemFromFormManager(String fileLink, String crfOid, String formLayoutOid) {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<byte[]> response = restTemplate.exchange(fileLink, HttpMethod.GET, entity, byte[].class, "1");
FileItem fileItem = null;
if (response.getStatusCode() == HttpStatus.OK) {
String fileName = "";
FileOutputStream output = null;
try {
String disposition = response.getHeaders().get("Content-Disposition").get(0);
fileName = disposition.replaceFirst("(?i)^.*filename=\"([^\"]+)\".*$", "$1");
String dir = Utils.getCrfMediaFilePath(crfOid, formLayoutOid);
if (!new File(dir).exists()) {
new File(dir).mkdirs();
logger.debug("Made the directory " + dir);
}
File file = new File(dir + fileName);
output = new FileOutputStream(file);
IOUtils.write(response.getBody(), output);
fileItem = new DiskFileItem("media_file", response.getHeaders().get("Content-Type").get(0), false, fileName, 100000000, file);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return fileItem;
}
use of org.apache.commons.fileupload.disk.DiskFileItem in project ysoserial by frohoff.
the class FileUpload1 method makePayload.
private static DiskFileItem makePayload(int thresh, String repoPath, String filePath, byte[] data) throws IOException, Exception {
// if thresh < written length, delete outputFile after copying to repository temp file
// otherwise write the contents to repository temp file
File repository = new File(repoPath);
DiskFileItem diskFileItem = new DiskFileItem("test", "application/octet-stream", false, "test", 100000, repository);
File outputFile = new File(filePath);
DeferredFileOutputStream dfos = new DeferredFileOutputStream(thresh, outputFile);
OutputStream os = (OutputStream) Reflections.getFieldValue(dfos, "memoryOutputStream");
os.write(data);
Reflections.getField(ThresholdingOutputStream.class, "written").set(dfos, data.length);
Reflections.setFieldValue(diskFileItem, "dfos", dfos);
Reflections.setFieldValue(diskFileItem, "sizeThreshold", 0);
return diskFileItem;
}
use of org.apache.commons.fileupload.disk.DiskFileItem in project molgenis by molgenis.
the class ImportWizardControllerTest method createMultipartFile.
private MultipartFile createMultipartFile(String filename) throws IOException {
File file = new File("/src/test/resources/" + filename);
DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length(), file.getParentFile());
fileItem.getOutputStream();
return new CommonsMultipartFile(fileItem);
}
use of org.apache.commons.fileupload.disk.DiskFileItem 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.DiskFileItem in project oap by oaplatform.
the class WsFileUploader method handle.
@Override
@SneakyThrows
public void handle(Request request, Response response) {
val ctx = new RequestUploadContext(request);
if (FileUpload.isMultipartContent(ctx)) {
val items = upload.parseRequest(ctx);
if (items.stream().filter(i -> !i.isFormField()).count() != 1) {
log.trace("Only one file allowed");
response.respond(HttpResponse.status(HTTP_BAD_REQUEST, "Only one file allowed"));
return;
}
if (items.stream().filter(i -> i.isFormField() && "prefix".equals(i.getFieldName())).count() != 1) {
log.trace("'prefix' field is required");
response.respond(HttpResponse.status(HTTP_BAD_REQUEST, "'prefix' field is required"));
return;
}
val fileItem = items.stream().filter(i -> !i.isFormField()).findAny().get();
val prefixItem = items.stream().filter(FileItem::isFormField).findAny().get();
try {
val id = Cuid.next();
val prefix = prefixItem.getString();
val fileName = fileItem.getName();
val file = new Media((prefix.endsWith("/") ? prefix + id : prefix + "/" + id) + "." + FilenameUtils.getExtension(fileName), fileName, fileItem.getContentType(), ((DiskFileItem) fileItem).getStoreLocation().toPath());
log.debug("new file = {}, isInMemory = {}", file, fileItem.isInMemory());
if (fileItem.isInMemory()) {
fileItem.write(file.path.toFile());
}
val mediaInfo = new MediaInfo();
val mediaContext = new MediaContext();
val media = Stream.of(postprocessing).foldLeft(file, (f, p) -> p.process(f, mediaInfo, mediaContext));
if (log.isTraceEnabled()) {
log.trace("media = {}", media);
log.trace("info = {}", mediaInfo);
log.trace("context = {}", mediaContext);
}
fireUploaded(media, mediaInfo, mediaContext);
response.respond(HttpResponse.ok(new MediaResponse(media.id, mediaInfo)));
} finally {
Files.deleteIfExists(((DiskFileItem) fileItem).getStoreLocation().toPath());
}
} else {
response.respond(HttpResponse.NOT_FOUND);
}
}
Aggregations