Search in sources :

Example 1 with DiskFileItem

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;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) HttpEntity(org.springframework.http.HttpEntity) FileOutputStream(java.io.FileOutputStream) RestTemplate(org.springframework.web.client.RestTemplate) ByteArrayHttpMessageConverter(org.springframework.http.converter.ByteArrayHttpMessageConverter) IOException(java.io.IOException) File(java.io.File) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem)

Example 2 with DiskFileItem

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;
}
Also used : ThresholdingOutputStream(org.apache.commons.io.output.ThresholdingOutputStream) OutputStream(java.io.OutputStream) DeferredFileOutputStream(org.apache.commons.io.output.DeferredFileOutputStream) ThresholdingOutputStream(org.apache.commons.io.output.ThresholdingOutputStream) DeferredFileOutputStream(org.apache.commons.io.output.DeferredFileOutputStream) File(java.io.File) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem)

Example 3 with 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);
}
Also used : File(java.io.File) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile)

Example 4 with DiskFileItem

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);
}
Also used : ObjectId(org.bson.types.ObjectId) BasicBSONObject(org.bson.BasicBSONObject) BSONObject(org.bson.BSONObject) ArrayList(java.util.ArrayList) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) BasicBSONObject(org.bson.BasicBSONObject) FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) BasicDBObject(com.mongodb.BasicDBObject) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) BasicBSONObject(org.bson.BasicBSONObject) BasicDBObject(com.mongodb.BasicDBObject) BSONObject(org.bson.BSONObject) FileUploadException(org.apache.commons.fileupload.FileUploadException) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem)

Example 5 with DiskFileItem

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);
    }
}
Also used : lombok.val(lombok.val) FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) SneakyThrows(lombok.SneakyThrows)

Aggregations

DiskFileItem (org.apache.commons.fileupload.disk.DiskFileItem)8 File (java.io.File)6 IOException (java.io.IOException)5 FileItem (org.apache.commons.fileupload.FileItem)5 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)3 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)3 FileOutputStream (java.io.FileOutputStream)2 BasicDBObject (com.mongodb.BasicDBObject)1 GraphicalView (com.serotonin.m2m2.gviews.GraphicalView)1 User (com.serotonin.m2m2.vo.User)1 XWikiException (com.xpn.xwiki.XWikiException)1 OutputStream (java.io.OutputStream)1 ArrayList (java.util.ArrayList)1 SneakyThrows (lombok.SneakyThrows)1 lombok.val (lombok.val)1 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)1 FileUpload (org.apache.commons.fileupload.FileUpload)1 FileUploadBase (org.apache.commons.fileupload.FileUploadBase)1 FileUploadException (org.apache.commons.fileupload.FileUploadException)1 RequestContext (org.apache.commons.fileupload.RequestContext)1