Example usage for org.apache.commons.fileupload FileItem getInputStream

List of usage examples for org.apache.commons.fileupload FileItem getInputStream

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getInputStream.

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Returns an java.io.InputStream InputStream that can be used to retrieve the contents of the file.

Usage

From source file:com.afis.jx.ckfinder.connector.handlers.command.FileUploadCommand.java

/**
 * saves temporary file in the correct file path.
 *
 * @param path path to save file//from   w  w w .  j  a v a  2 s  . com
 * @param item file upload item
 * @return result of saving, true if saved correctly
 * @throws Exception when error occurs.
 */
private boolean saveTemporaryFile(final String path, final FileItem item) throws Exception {
    File file = new File(path, this.newFileName);

    AfterFileUploadEventArgs args = new AfterFileUploadEventArgs();
    args.setCurrentFolder(this.currentFolder);
    args.setFile(file);
    args.setFileContent(item.get());
    if (!ImageUtils.isImage(file)) {
        item.write(file);
        if (configuration.getEvents() != null) {
            configuration.getEvents().run(EventTypes.AfterFileUpload, args, configuration);
        }
        return true;
    } else if (ImageUtils.checkImageSize(item.getInputStream(), this.configuration)
            || configuration.checkSizeAfterScaling()) {
        ImageUtils.createTmpThumb(item.getInputStream(), file, getFileItemName(item), this.configuration);
        if (!configuration.checkSizeAfterScaling()
                || FileUtils.checkFileSize(configuration.getTypes().get(this.type), file.length())) {
            if (configuration.getEvents() != null) {
                configuration.getEvents().run(EventTypes.AfterFileUpload, args, configuration);
            }
            return true;
        } else {
            file.delete();
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG;
            return false;
        }
    } else {
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG;
        return false;
    }
}

From source file:com.patrolpro.servlet.UploadPostOrderServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww w .j  a  v  a 2s  . c  om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        String companyId = request.getParameter("companyId");
        String clientId = request.getParameter("clientId");
        String cid = request.getParameter("cid");

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        List<FileItem> fields = upload.parseRequest(request);

        FileItem fileData = null;
        for (int f = 0; f < fields.size(); f++) {
            if (fields.get(f).getFieldName().equals("file_data")) {
                fileData = fields.get(f);
            } else if (fields.get(f).getFieldName().equals("companyId")) {
                companyId = fields.get(f).getString();
            } else if (fields.get(f).getFieldName().equals("clientId")) {
                clientId = fields.get(f).getString();
            } else if (fields.get(f).getFieldName().equals("cid")) {
                cid = fields.get(f).getString();
            }
        }

        File tempFile = File.createTempFile("postinstr", "tmnp");
        tempFile.deleteOnExit();

        CompanyService compService = new CompanyService();
        CompanyObj comp = compService.getCompanyObjById(Integer.parseInt(companyId));

        FileOutputStream oStream = new FileOutputStream(tempFile);
        InputStream iStream = fileData.getInputStream();
        byte[] buffer = new byte[2048];
        int numRead = 0;
        while ((numRead = iStream.read(buffer)) > -1) {
            oStream.write(buffer, 0, numRead);
        }
        oStream.flush();
        oStream.close();
        iStream.close();

        boolean isSuccesfull = FileLoader.saveAdditionalFile("location_additional_files", comp.getCompanyDb(),
                clientId, fileData.getName(), tempFile);
        tempFile.delete();

        response.sendRedirect("/client/post_instructions.xhtml?windowId=" + cid);
    } catch (Exception exe) {
        exe.printStackTrace();
    } finally {

    }
}

From source file:edu.um.umflix.stubs.UploadServletStub.java

protected List<FileItem> getFileItems(HttpServletRequest request) throws FileUploadException {
    if (error.equals("fileUpload"))
        new FileUploadException();

    File file = null;/*from ww  w.  j  a  va  2s  .  co  m*/
    FileItem item1 = null;
    List<FileItem> list = new ArrayList<FileItem>();
    for (int i = 0; i < fields.length; i++) {
        FileItem item = Mockito.mock(FileItem.class);
        Mockito.when(item.isFormField()).thenReturn(true);
        Mockito.when(item.getFieldName()).thenReturn(fields[i]);
        if (fields[i].equals("premiere") || fields[i].equals("endDate") || fields[i].equals("startDate")) {
            Mockito.when(item.getString()).thenReturn("2013-06-01");
        } else {
            Mockito.when(item.getString()).thenReturn("11");
        }
        if (fields[i].equals("premiere") && error.equals("date"))
            Mockito.when(item.getString()).thenReturn("11");
        if (fields[i].equals("clipduration0")) {
            Mockito.when(item.getString()).thenReturn("01:22:01");
        }
        list.add(item);
    }
    try {
        file = File.createTempFile("aaaa", "aaaatest");
        item1 = Mockito.mock(FileItem.class);
        Mockito.when(item1.getInputStream()).thenReturn(new FileInputStream(file));

    } catch (IOException e) {
        e.printStackTrace();
    }

    list.add(item1);
    FileItem token = Mockito.mock(FileItem.class);
    Mockito.when(token.isFormField()).thenReturn(true);
    Mockito.when(token.getFieldName()).thenReturn("token");
    if (error.equals("token")) {
        Mockito.when(token.getString()).thenReturn("invalidToken");
    } else
        Mockito.when(token.getString()).thenReturn("validToken");

    list.add(token);

    return list;
}

From source file:ea.ejb.AbstractFacade.java

public Map<String, String> obtenerDatosFormConImagen(HttpServletRequest request) {

    Map<String, String> mapDatos = new HashMap();

    final String SAVE_DIR = "uploadImages";

    // Parametros del form
    String description = null;//from  w  w  w .j a  v a 2 s  .com
    String url_image = null;
    String id_grupo = null;

    boolean isMultiPart;
    String filePath;
    int maxFileSize = 50 * 1024;
    int maxMemSize = 4 * 1024;
    File file = null;
    InputStream inputStream = null;
    OutputStream outputStream = null;

    // gets absolute path of the web application
    String appPath = request.getServletContext().getRealPath("");
    // constructs path of the directory to save uploaded file
    filePath = appPath + File.separator + "assets" + File.separator + "img" + File.separator + SAVE_DIR;
    String filePathWeb = "assets/img/" + SAVE_DIR + "/";
    // creates the save directory if it does not exists
    File fileSaveDir = new File(filePath);

    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdir();
    }
    // Check that we have a file upload request
    isMultiPart = ServletFileUpload.isMultipartContent(request);
    if (isMultiPart) {

        // Parse the request
        List<FileItem> items = getMultipartItems(request);

        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        int offset = 0;
        int leidos = 0;
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {
                // ProcessFormField
                String name = item.getFieldName();
                String value = item.getString();
                if (name.equals("description_post_grupo") || name.equals("descripcion")) {
                    description = value;
                } else if (name.equals("id_grupo")) {
                    id_grupo = value;
                }
            } else {
                // ProcessUploadedFile
                try {
                    String itemName = item.getName();
                    if (!itemName.equals("")) {
                        url_image = filePathWeb + item.getName();
                        // read this file into InputStream
                        inputStream = item.getInputStream();
                        // write the inputStream to a FileOutputStream
                        if (file == null) {
                            String fileDirUpload = filePath + File.separator + item.getName();
                            file = new File(fileDirUpload);
                            // crea el archivo en el sistema
                            file.createNewFile();
                            if (file.exists()) {
                                outputStream = new FileOutputStream(file);
                            }
                        }

                        int read = 0;
                        byte[] bytes = new byte[1024];

                        while ((read = inputStream.read(bytes)) != -1) {
                            outputStream.write(bytes, offset, read);
                            leidos += read;
                        }
                        offset += leidos;
                        leidos = 0;
                        System.out.println("Done!");
                    } else {
                        url_image = "";
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        if (outputStream != null) {
            try {
                // outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
    mapDatos.put("descripcion", description);
    mapDatos.put("imagen", url_image);
    mapDatos.put("id_grupo", id_grupo);

    return mapDatos;
}

From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.JobSubmitServlet.java

private Long submitJob(HttpServletRequest request, Principal principal)
        throws FileUploadException, IOException, ClientException, ParseException {

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

    /*//from  w w  w. ja v  a2s .c  om
     *Set the size threshold, above which content will be stored on disk.
     */
    fileItemFactory.setSizeThreshold(5 * 1024 * 1024); //5 MB
    /*
     * Set the temporary directory to store the uploaded files of size above threshold.
     */
    fileItemFactory.setRepository(this.tmpDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    /*
     * Parse the request
     */
    List items = uploadHandler.parseRequest(request);
    Properties fields = new Properties();
    for (Iterator itr = items.iterator(); itr.hasNext();) {
        FileItem item = (FileItem) itr.next();
        /*
         * Handle Form Fields.
         */
        if (item.isFormField()) {
            fields.setProperty(item.getFieldName(), item.getString());
        }
    }

    JobSpec jobSpec = MAPPER.readValue(fields.getProperty("jobSpec"), JobSpec.class);

    for (Iterator itr = items.iterator(); itr.hasNext();) {
        FileItem item = (FileItem) itr.next();
        if (!item.isFormField()) {
            //Handle Uploaded files.
            log("Spreadsheet upload for user " + principal.getName() + ": Field Name = " + item.getFieldName()
                    + ", File Name = " + item.getName() + ", Content type = " + item.getContentType()
                    + ", File Size = " + item.getSize());
            if (item.getSize() > 0) {
                InputStream is = item.getInputStream();
                try {
                    this.servicesClient.upload(FilenameUtils.getName(item.getName()),
                            jobSpec.getSourceConfigId(), item.getFieldName(), is);
                    log("File '" + item.getName() + "' uploaded successfully");
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException ignore) {
                        }
                    }
                }
            } else {
                log("File '" + item.getName() + "' ignored because it was zero length");
            }
        }
    }

    URI uri = this.servicesClient.submitJob(jobSpec);
    String uriStr = uri.toString();
    Long jobId = Long.valueOf(uriStr.substring(uriStr.lastIndexOf("/") + 1));
    log("Job " + jobId + " submitted for user " + principal.getName());
    return jobId;
}

From source file:net.fckeditor.connector.MyDispatcher.java

/**
 * Called by the connector servlet to handle a {@code POST} request. In
 * particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and
 * {@link Command#QUICK_UPLOAD QuickUpload} commands.
 * /*from w  ww .j  a va2  s .  c o m*/
 * @param request
 *            the current request instance
 * @return the upload response instance associated with this request
 */
UploadResponse doPost(final HttpServletRequest request) {
    logger.debug("Entering Dispatcher#doPost");

    Context context = ThreadLocalData.getContext();
    context.logBaseParameters();

    UploadResponse uploadResponse = null;
    // check permissions for user actions
    if (!RequestCycleHandler.isFileUploadEnabled(request))
        uploadResponse = UploadResponse.getFileUploadDisabledError();
    // check parameters  
    else if (!Command.isValidForPost(context.getCommandStr()))
        uploadResponse = UploadResponse.getInvalidCommandError();
    else if (!ResourceType.isValidType(context.getTypeStr()))
        uploadResponse = UploadResponse.getInvalidResourceTypeError();
    else if (!UtilsFile.isValidPath(context.getCurrentFolderStr()))
        uploadResponse = UploadResponse.getInvalidCurrentFolderError();
    else {

        // call the Connector#fileUpload
        ResourceType type = context.getDefaultResourceType();
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        try {
            List<FileItem> items = upload.parseRequest(request);
            // We upload just one file at the same time
            FileItem uplFile = items.get(0);
            // Some browsers transfer the entire source path not just the
            // filename
            String fileName = FilenameUtils.getName(uplFile.getName());
            fileName = UUID.randomUUID().toString().replace("-", "") + "."
                    + FilenameUtils.getExtension(fileName);
            logger.debug("Parameter NewFile: {}", fileName);
            // check the extension
            if (type.isDeniedExtension(FilenameUtils.getExtension(fileName)))
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            // Secure image check (can't be done if QuickUpload)
            else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads()
                    && !UtilsFile.isImage(uplFile.getInputStream())) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else {
                String sanitizedFileName = UtilsFile.sanitizeFileName(fileName);
                logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName);
                String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(),
                        sanitizedFileName, uplFile.getInputStream());
                String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type,
                        context.getCurrentFolderStr(), newFileName);

                if (sanitizedFileName.equals(newFileName))
                    uploadResponse = UploadResponse.getOK(fileUrl);
                else {
                    uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName);
                    logger.debug("Parameter NewFile (renamed): {}", newFileName);
                }
            }

            uplFile.delete();
        } catch (InvalidCurrentFolderException e) {
            uploadResponse = UploadResponse.getInvalidCurrentFolderError();
        } catch (WriteException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (IOException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (FileUploadException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        }
    }

    logger.debug("Exiting Dispatcher#doPost");
    return uploadResponse;
}

From source file:com.silverpeas.form.displayers.FileFieldDisplayer.java

private SimpleDocument createSimpleDocument(String objectId, String componentId, FileItem item,
        String logicalName, String userId, boolean versionned) throws IOException {
    SimpleDocumentPK documentPk = new SimpleDocumentPK(null, componentId);
    SimpleDocument document;//from w w  w .  ja  va 2 s  . c o m
    if (versionned) {
        document = new HistorisedDocument(documentPk, objectId, 0, new SimpleAttachment(logicalName, null, null,
                null, item.getSize(), FileUtil.getMimeType(logicalName), userId, new Date(), null));
    } else {
        document = new SimpleDocument(documentPk, objectId, 0, false, null, new SimpleAttachment(logicalName,
                null, null, null, item.getSize(), FileUtil.getMimeType(logicalName), userId, new Date(), null));
    }
    document.setDocumentType(DocumentType.form);
    InputStream in = item.getInputStream();
    try {
        return AttachmentServiceFactory.getAttachmentService().createAttachment(document, in, false);
    } finally {
        IOUtils.closeQuietly(in);
    }

}

From source file:com.boundlessgeo.geoserver.api.controllers.IconController.java

@RequestMapping(value = "/{wsName:.+}", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public @ResponseStatus(value = HttpStatus.CREATED) @ResponseBody JSONArr create(@PathVariable String wsName,
        HttpServletRequest request) throws IOException, FileUploadException {

    WorkspaceInfo ws;//from w w  w  .  jav  a  2 s .c  o m
    Resource styles;

    if (wsName == null) {
        ws = null;
        styles = dataDir().getRoot("styles");
    } else {
        ws = findWorkspace(wsName, catalog());
        styles = dataDir().get(ws, "styles");
    }

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    @SuppressWarnings("unchecked")
    List<FileItem> input = (List<FileItem>) upload.parseRequest(request);

    JSONArr created = new JSONArr();
    for (FileItem file : input) {
        String filename = file.getName();

        // trim filename if required
        if (filename.lastIndexOf('/') != -1) {
            filename = filename.substring(filename.lastIndexOf('/'));
        }
        if (filename.lastIndexOf('\\') != -1) {
            filename = filename.substring(filename.lastIndexOf('\\'));
        }
        String ext = fileExt(filename);
        if (!ICON_FORMATS.containsKey(ext)) {
            String msg = "Icon " + filename + " format " + ext + " unsupported - try:" + ICON_FORMATS.keySet();
            LOG.warning(msg);
            throw new FileUploadException(msg);
        }
        try {
            InputStream data = file.getInputStream();
            Resources.copy(data, styles, filename);

            icon(created.addObject(), ws, styles.get(filename), request);
        } catch (Exception e) {
            throw new FileUploadException("Unable to write " + filename, e);
        }
    }

    return created;
}

From source file:com.kmetop.demsy.modules.ckfinder.FileUploadCommand.java

/**
 * saves temporary file in the correct file path.
 * /*from w  w  w. j  a  va 2 s  .c  o m*/
 * @param path
 *            path to save file
 * @param item
 *            file upload item
 * @return result of saving, true if saved correctly
 * @throws Exception
 *             when error occurs.
 */
private boolean saveTemporaryFile(final String path, final FileItem item) throws Exception {
    File file = new File(path, this.newFileName);

    AfterFileUploadEventArgs args = new AfterFileUploadEventArgs();
    args.setCurrentFolder(this.currentFolder);
    args.setFile(file);
    args.setFileContent(item.get());
    if (!ImageUtils.isImage(file)) {
        item.write(file);
        if (configuration.getEvents() != null) {
            configuration.getEvents().run(EventTypes.AfterFileUpload, args, configuration);
        }
        return true;
    } else if (ImageUtils.checkImageSize(item.getInputStream(), this.configuration)) {

        ImageUtils.createTmpThumb(item.getInputStream(), file, getFileItemName(item), this.configuration);
        if (configuration.getEvents() != null) {
            configuration.getEvents().run(EventTypes.AfterFileUpload, args, configuration);
        }
        return true;
    } else if (configuration.checkSizeAfterScaling()) {
        ImageUtils.createTmpThumb(item.getInputStream(), file, getFileItemName(item), this.configuration);
        if (FileUtils.checkFileSize(configuration.getTypes().get(this.type), file.length())) {
            if (configuration.getEvents() != null) {
                configuration.getEvents().run(EventTypes.AfterFileUpload, args, configuration);
            }
            return true;
        } else {
            file.delete();
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG;
            return false;
        }
    }
    // should be unreacheable
    return false;
}

From source file:com.portfolio.data.attachment.FileServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // =====================================================================================
    initialize(request);//www. j  av  a2 s .c  om

    int userId = 0;
    int groupId = 0;
    String user = "";

    HttpSession session = request.getSession(true);
    if (session != null) {
        Integer val = (Integer) session.getAttribute("uid");
        if (val != null)
            userId = val;
        val = (Integer) session.getAttribute("gid");
        if (val != null)
            groupId = val;
        user = (String) session.getAttribute("user");
    }

    Credential credential = null;
    Connection c = null;
    try {
        //On initialise le dataProvider
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    /// uuid: celui de la ressource

    /// /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]]

    String origin = request.getRequestURL().toString();

    /// Rcupration des paramtres
    String url = request.getPathInfo();
    String[] token = url.split("/");
    String uuid = token[1];

    String size = request.getParameter("size");
    if (size == null)
        size = "S";

    String lang = request.getParameter("lang");
    if (lang == null) {
        lang = "fr";
    }

    /// Vrification des droits d'accs
    if (!credential.hasNodeRight(userId, groupId, uuid, Credential.WRITE)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        //throw new Exception("L'utilisateur userId="+userId+" n'a pas le droit WRITE sur le noeud "+nodeUuid);
    }

    String data;
    String fileid = "";
    try {
        data = dataProvider.getResNode(uuid, userId, groupId);

        /// Parse les donnes
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader("<node>" + data + "</node>"));
        Document doc = documentBuilder.parse(is);
        DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation().getFeature("LS", "3.0");
        LSSerializer serial = impl.createLSSerializer();
        serial.getDomConfig().setParameter("xml-declaration", false);

        /// Cherche si on a dj envoy quelque chose
        XPath xPath = XPathFactory.newInstance().newXPath();
        String filterRes = "//filename[@lang=\"" + lang + "\"]";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

        String filename = "";
        if (nodelist.getLength() > 0)
            filename = nodelist.item(0).getTextContent();

        if (!"".equals(filename)) {
            /// Already have one, per language
            String filterId = "//fileid[@lang='" + lang + "']";
            NodeList idlist = (NodeList) xPath.compile(filterId).evaluate(doc, XPathConstants.NODESET);
            if (idlist.getLength() != 0) {
                Element fileNode = (Element) idlist.item(0);
                fileid = fileNode.getTextContent();
            }
        }
    } catch (Exception e2) {
        e2.printStackTrace();
    }

    int last = fileid.lastIndexOf("/") + 1; // FIXME temp patch
    if (last < 0)
        last = 0;
    fileid = fileid.substring(last);
    /// request.getHeader("REFERRER");

    /// criture des donnes
    String urlTarget = "http://" + server + "/" + fileid;
    //      String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";

    // Unpack form, fetch binary data and send
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Configure a repository (to ensure a secure temp location is used)
    /*
    ServletContext servletContext = this.getServletConfig().getServletContext();
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    factory.setRepository(repository);
    //*/

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    String json = "";
    HttpURLConnection connection = null;
    // 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 ("uploadfile".equals(item.getFieldName())) {
                // Send raw data
                InputStream inputData = item.getInputStream();

                /*
                URL urlConn = new URL(urlTarget);
                connection = (HttpURLConnection) urlConn.openConnection();
                connection.setDoOutput(true);
                connection.setUseCaches(false);                 /// We don't want to cache data
                connection.setInstanceFollowRedirects(false);   /// Let client follow any redirection
                String method = request.getMethod();
                connection.setRequestMethod(method);
                        
                String context = request.getContextPath();
                connection.setRequestProperty("app", context);
                //*/

                String fileName = item.getName();
                long filesize = item.getSize();
                String contentType = item.getContentType();

                //               /*
                connection = CreateConnection(urlTarget, request);
                connection.setRequestProperty("filename", uuid);
                connection.setRequestProperty("content-type", "application/octet-stream");
                connection.setRequestProperty("content-length", Long.toString(filesize));
                //*/
                connection.connect();

                OutputStream outputData = connection.getOutputStream();
                IOUtils.copy(inputData, outputData);

                /// Those 2 lines are needed, otherwise, no request sent
                int code = connection.getResponseCode();
                String msg = connection.getResponseMessage();

                InputStream objReturn = connection.getInputStream();
                StringWriter idResponse = new StringWriter();
                IOUtils.copy(objReturn, idResponse);
                fileid = idResponse.toString();

                connection.disconnect();

                /// Construct Json
                StringWriter StringOutput = new StringWriter();
                JsonWriter writer = new JsonWriter(StringOutput);
                writer.beginObject();
                writer.name("files");
                writer.beginArray();
                writer.beginObject();

                writer.name("name").value(fileName);
                writer.name("size").value(filesize);
                writer.name("type").value(contentType);
                writer.name("url").value(origin);
                writer.name("fileid").value(fileid);
                //                               writer.name("deleteUrl").value(ref);
                //                                       writer.name("deleteType").value("DELETE");
                writer.endObject();

                writer.endArray();
                writer.endObject();

                writer.close();

                json = StringOutput.toString();

                /*
                DataOutputStream datawriter = new DataOutputStream(connection.getOutputStream());
                byte[] buffer = new byte[1024];
                int dataSize;
                while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
                {
                   datawriter.write(buffer, 0, dataSize);
                }
                datawriter.flush();
                datawriter.close();
                //*/
                //               outputData.close();
                //               inputData.close();

                break;
            }
        }
    } catch (FileUploadException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    /*
    HttpURLConnection connection = CreateConnection( urlTarget, request );
            
    connection.setRequestProperty("referer", origin);
            
    /// Send post data
    ServletInputStream inputData = request.getInputStream();
    DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
            
    byte[] buffer = new byte[1024];
    int dataSize;
    while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
    {
       writer.write(buffer, 0, dataSize);
    }
    inputData.close();
    writer.close();
            
    /// So we can forward some Set-Cookie
    String ref = request.getHeader("referer");
            
    /// Prend le JSON du fileserver
    InputStream in = connection.getInputStream();
            
    InitAnswer(connection, response, ref);
            
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    StringBuilder builder = new StringBuilder();
    for( String line = null; (line = reader.readLine()) != null; )
       builder.append(line).append("\n");
    //*/

    /// Envoie la mise  jour au backend
    /*
    try
    {
       PostForm.updateResource(session.getId(), backend, uuid, lang, json);
    }
    catch( Exception e )
    {
       e.printStackTrace();
    }
    //*/

    connection.disconnect();
    /// Renvoie le JSON au client
    response.setContentType("application/json");
    PrintWriter respWriter = response.getWriter();
    respWriter.write(json);

    //      RetrieveAnswer(connection, response, ref);
    dataProvider.disconnect();
}