Example usage for javax.servlet.http Part getInputStream

List of usage examples for javax.servlet.http Part getInputStream

Introduction

In this page you can find the example usage for javax.servlet.http Part getInputStream.

Prototype

public InputStream getInputStream() throws IOException;

Source Link

Document

Gets the content of this part as an InputStream

Usage

From source file:io.stallion.contentPublishing.UploadRequestProcessor.java

protected File writeMultiPartToLocalFile(U uploaded) throws IOException {
    stRequest.setAsMultiPartRequest();/*from  ww w .  j  a  va2 s .  co m*/

    final String path = stRequest.getParameter("destination");
    final Part filePart = stRequest.getPart("file");
    String fullFileName = getFileNameFromPart(filePart);
    String extension = FilenameUtils.getExtension(fullFileName);
    String fileName = truncate(fullFileName, 85);
    String relativePath = GeneralUtils.slugify(truncate(FilenameUtils.getBaseName(fullFileName), 75)) + "-"
            + DateUtils.mils() + "." + extension;
    relativePath = "stallion-file-" + uploaded.getId() + "/" + GeneralUtils.secureRandomToken(8) + "/"
            + relativePath;

    String destPath = uploadsFolder + relativePath;
    FileUtils.forceMkdir(new File(destPath).getParentFile());

    uploaded.setCloudKey(relativePath).setExtension(extension).setName(fileName)
            .setOwnerId(Context.getUser().getId()).setUploadedAt(DateUtils.utcNow())
            .setType(fileController.getTypeForExtension(extension));

    // Make raw URL
    String url = makeRawUrlForFile(uploaded, "org");
    uploaded.setRawUrl(url);

    fileController.save(uploaded);

    OutputStream out = null;
    InputStream filecontent = null;
    boolean failed = true;
    File outFile = new File(destPath);
    Long amountRead = 0L;
    Long maxSize = Settings.instance().getUserUploads().getMaxFileSizeBytes();
    try {
        out = new FileOutputStream(destPath);
        filecontent = filePart.getInputStream();

        int read = 0;
        final byte[] bytes = new byte[1024];
        while ((read = filecontent.read(bytes)) != -1) {
            amountRead += read;
            if (amountRead > maxSize) {
                throw new ClientException("Uploaded file exceeded max size of " + maxSize + " bytes.");
            }
            out.write(bytes, 0, read);
        }
        failed = false;
        Log.info("File{0}being uploaded to {1}", new Object[] { fileName, path });
        uploaded.setSizeBytes(amountRead);
    } finally {
        if (out != null) {
            out.close();
        }
        if (filecontent != null) {
            filecontent.close();
        }
        if (failed) {
            if (outFile.exists()) {
                outFile.delete();
            }
        }
    }
    return new File(destPath);
}

From source file:org.eclipse.packagedrone.repo.channel.web.channel.ChannelController.java

@RequestMapping(value = "/channel/{channelId}/artifact/{artifactId}/attach", method = RequestMethod.POST)
public ModelAndView attachArtifactPost(@PathVariable("channelId") final String channelId,
        @PathVariable("artifactId") final String artifactId,
        @RequestParameter(required = false, value = "name") final String name,
        final @RequestParameter("file") Part file) {
    return withChannel(channelId, ModifiableChannel.class, channel -> {

        String targetName = name;

        final Optional<ChannelArtifactInformation> parentArtifact = channel.getArtifact(artifactId);
        if (!parentArtifact.isPresent()) {
            return CommonController.createNotFound("artifact", artifactId);
        }/* w ww. j  a v a 2  s . c om*/

        try {
            if (targetName == null || targetName.isEmpty()) {
                targetName = file.getSubmittedFileName();
            }

            channel.getContext().createArtifact(artifactId, file.getInputStream(), targetName, null);
        } catch (final IOException e) {
            return new ModelAndView("/error/upload");
        }

        return new ModelAndView(
                "redirect:/channel/" + UrlEscapers.urlPathSegmentEscaper().escape(channelId) + "/view");
    });
}

From source file:ips1ap101.lib.core.jsf.JSF.java

public static CampoArchivoMultiPart upload(Part part, String carpeta, EnumOpcionUpload opcion)
        throws Exception {
    Bitacora.trace(JSF.class, "upload", part, carpeta, opcion);
    if (part == null) {
        return null;
    }/*  ww  w . ja  v  a 2s . co m*/
    if (part.getSize() == 0) {
        return null;
    }
    String originalName = getPartFileName(part);
    if (StringUtils.isBlank(originalName)) {
        return null;
    }
    CampoArchivoMultiPart campoArchivo = new CampoArchivoMultiPart();
    campoArchivo.setPart(part);
    campoArchivo.setClientFileName(null);
    campoArchivo.setServerFileName(null);
    /**/
    Bitacora.trace(JSF.class, "upload", "name=" + part.getName());
    Bitacora.trace(JSF.class, "upload", "type=" + part.getContentType());
    Bitacora.trace(JSF.class, "upload", "size=" + part.getSize());
    /**/
    String sep = System.getProperties().getProperty("file.separator");
    String validChars = StrUtils.VALID_CHARS;
    String filepath = null;
    if (STP.esIdentificadorArchivoValido(carpeta)) {
        filepath = carpeta.replace(".", sep);
    }
    long id = LongUtils.getNewId();
    //      String filename = STP.getRandomString();
    String filename = id + "";
    String pathname = Utils.getAttachedFilesDir(filepath) + filename;
    String ext = Utils.getExtensionArchivo(originalName);
    if (StringUtils.isNotBlank(ext)) {
        String str = ext.toLowerCase();
        if (StringUtils.containsOnly(str, validChars)) {
            filename += "." + str;
            pathname += "." + str;
        }
    }
    /**/
    //      part.write(pathname);
    /**/
    //      OutputStream outputStream = new FileOutputStream(pathname);
    //      outputStream.write(IOUtils.readFully(part.getInputStream(), -1, false));
    /**/
    int bytesRead;
    int bufferSize = 8192;
    byte[] bytes = null;
    byte[] buffer = new byte[bufferSize];
    try (InputStream input = part.getInputStream(); OutputStream output = new FileOutputStream(pathname)) {
        while ((bytesRead = input.read(buffer)) != -1) {
            if (!EnumOpcionUpload.FILA.equals(opcion)) {
                output.write(buffer, 0, bytesRead);
            }
            if (!EnumOpcionUpload.ARCHIVO.equals(opcion)) {
                if (bytesRead < bufferSize) {
                    bytes = ArrayUtils.addAll(bytes, ArrayUtils.subarray(buffer, 0, bytesRead));
                } else {
                    bytes = ArrayUtils.addAll(bytes, buffer);
                }
            }
        }
    }
    /**/
    String clientFilePath = null;
    String clientFileName = clientFilePath == null ? originalName : clientFilePath + originalName;
    String serverFileName = Utils.getWebServerRelativePath(pathname);
    if (!EnumOpcionUpload.ARCHIVO.equals(opcion)) {
        String contentType = part.getContentType();
        long size = part.getSize();
        insert(id, clientFileName, serverFileName, contentType, size, bytes);
    }
    campoArchivo.setClientFileName(clientFileName);
    campoArchivo.setServerFileName(serverFileName);
    return campoArchivo;
}

From source file:com.crushpaper.Servlet.java

/** Part of the HTML API. Handle a restore. */
private void handleHtmlDoUserRestore(RequestAndResponse requestAndResponse)
        throws IOException, ServletException {
    final Errors errors = new Errors();
    final Part part = requestAndResponse.request.getPart("file");

    final boolean reuseIds = getCheckBoxValue(requestAndResponse, "reuseIds");
    final boolean msWordListFormat = getCheckBoxValue(requestAndResponse, "msWordListFormat");

    final String csrft = requestAndResponse.getParameter("csrft");

    addIFrameHeader(requestAndResponse);

    if (isTheCsrftWrong(requestAndResponse, csrft)) {
        requestAndResponse.print(servletText.errorRequiresSignIn(false));
    } else if (!isUserSignedIn(requestAndResponse)) {
        requestAndResponse.print(servletText.errorRequiresSignIn(false));
    } else if (isUsersAccountClosed(requestAndResponse)) {
        requestAndResponse.print(servletText.errorAccountIsClosed());
    } else if (part == null) {
        requestAndResponse.print(servletText.errorNoFileUploaded());
    } else {//from   ww  w  .jav a  2 s . c  om
        final InputStream stream = part.getInputStream();
        final InputStreamReader streamReader = new InputStreamReader(stream, Charset.forName("UTF-8"));

        boolean result = false;
        if (msWordListFormat) {
            result = dbLogic.restoreMsWordListFormatForUser(getEffectiveUserId(requestAndResponse),
                    streamReader, isUserAnAdmin(requestAndResponse), errors);
        } else {
            result = dbLogic.restoreJsonForUser(getEffectiveUserId(requestAndResponse), streamReader, reuseIds,
                    isUserAnAdmin(requestAndResponse), errors);
        }

        if (!result) {
            requestAndResponse.print(servletText.errorRestoreFailed() + "<br>");

            for (final String text : errors.getTexts()) {
                requestAndResponse.print(text);
                requestAndResponse.print("<br>");
            }
        } else {
            requestAndResponse.print(servletText.sentenceRestored());
        }

        // This is so that if this gets reloaded a page can actually be
        // loaded.
        requestAndResponse.print("<script type=\"text/javascript\">\n"
                + "history.replaceState(null, null, '/restoreFrame/');\n" + "</script>");

    }

    addIFrameFooter(requestAndResponse);
}