Example usage for javax.servlet.http Part getSubmittedFileName

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

Introduction

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

Prototype

public String getSubmittedFileName();

Source Link

Document

Gets the file name specified by the client

Usage

From source file:cheladocs.controlo.DocumentoServlet.java

private void doUpload(Part part, HttpServletRequest request) {
    try {//from  w  w  w .  ja  v a  2 s  .c  o m

        InputStream in = part.getInputStream();

        File f = new File("c:\\ficheiros_docs\\" + part.getSubmittedFileName());

        f.createNewFile();
        FileOutputStream out = new FileOutputStream(f);

        byte[] buffer = new byte[1024 * 1024 * 100];

        int length;

        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }
        out.close();
        in.close();

    } catch (IOException ex) {
        ex.printStackTrace(System.out);
    }
}

From source file:com.thoughtworks.go.apiv1.configrepooperations.ConfigRepoOperationsControllerV1.java

String preflight(Request req, Response res) throws IOException {
    ConfigRepoConfig repo = repoFromRequest(req);
    ConfigRepoPlugin plugin = pluginFromRequest(req);
    PartialConfigLoadContext context = configContext(repo);

    final PreflightResult result = new PreflightResult();

    try {//from www.j  ava  2 s .co m
        Collection<Part> uploads = req.raw().getParts();
        Map<String, String> contents = new LinkedHashMap<>();

        for (Part ul : uploads) {
            if (!"files[]".equals(ul.getName())) {
                continue;
            }

            StringWriter w = new StringWriter();
            IOUtils.copy(ul.getInputStream(), w, StandardCharsets.UTF_8);
            contents.put(ul.getSubmittedFileName(), w.toString());
        }

        if (contents.isEmpty()) {
            result.update(Collections.singletonList(
                    "No file content provided; check to make sure you POST the form data as `files[]=`"),
                    false);
        } else {
            PartialConfig partialConfig = plugin.parseContent(contents, context);
            partialConfig.setOrigins(adHocConfigOrigin(repo));
            CruiseConfig config = partialConfigService.merge(partialConfig,
                    context.configMaterial().getFingerprint(), gcs.clonedConfigForEdit());

            gcs.validateCruiseConfig(config);
            result.update(Collections.emptyList(), true);
        }
    } catch (RecordNotFoundException e) {
        throw e;
    } catch (InvalidPartialConfigException e) {
        result.update(Collections.singletonList(e.getErrors()), false);
    } catch (GoConfigInvalidException e) {
        result.update(e.getAllErrors(), false);
    } catch (Exception e) {
        throw HaltApiResponses.haltBecauseOfReason(e.getMessage());
    }

    return writerForTopLevelObject(req, res, w -> PreflightResultRepresenter.toJSON(w, result));
}

From source file:cheladocs.controlo.DocumentoServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/pdf; application/msword; application/excel");

    String comando = request.getParameter("comando");

    if (comando == null) {
        comando = "principal";
    }//  ww  w .  ja v  a  2  s . c  o m

    DocumentoDAO documentoDAO;
    Documento documento = new Documento();

    if (comando == null || !comando.equalsIgnoreCase("principal")) {
        try {
            idDocumento = request.getParameter("numero_protocolo");
            if (idDocumento != null) {
                documento.setNumeroProtocolo(Integer.parseInt(idDocumento));
            }

        } catch (NumberFormatException ex) {
            System.err.println("Erro ao converter dado: " + ex.getMessage());
        }
    }

    try {

        documentoDAO = new DocumentoDAO();

        if (comando.equalsIgnoreCase("guardar")) {

            documento.getRequerente().setIdRequerente(Integer.parseInt(request.getParameter("requerente")));
            documento.setDataEntrada(Date.valueOf(request.getParameter("data_entrada")));
            documento.setOrigem(request.getParameter("origem_documento"));
            documento.setDescricaoAssunto(request.getParameter("descricao_assunto"));
            documento.getNaturezaAssunto()
                    .setIdNaturezaAssunto(Integer.parseInt(request.getParameter("natureza_assunto")));
            documento.getTipoExpediente()
                    .setIdTipoExpediente(Integer.parseInt(request.getParameter("tipo_expediente")));
            Part ficheiro = request.getPart("ficheiro");
            if (ficheiro != null) {
                byte[] ficheiroDados = IOUtils.toByteArray(ficheiro.getInputStream());
                documento.setConteudoDocumento(ficheiroDados);
                documento.setUrlFicheiroDocumento(ficheiro.getSubmittedFileName());
                doUpload(ficheiro, request);
            }
            documentoDAO.save(documento);
            response.sendRedirect("paginas/gerir_documento.jsp");

        } else if (comando.equalsIgnoreCase("editar")) {

            documento.setNumeroProtocolo(Integer.parseInt(request.getParameter("requerente")));

            documento.getRequerente().setIdRequerente(Integer.parseInt(request.getParameter("requerente")));
            documento.setDataEntrada(Date.valueOf(request.getParameter("data_entrada")));
            documento.setOrigem(request.getParameter("origem_documento"));
            documento.setDescricaoAssunto(request.getParameter("descricao_assunto"));
            documento.getNaturezaAssunto()
                    .setIdNaturezaAssunto(Integer.parseInt(request.getParameter("natureza_assunto")));
            documento.getTipoExpediente()
                    .setIdTipoExpediente(Integer.parseInt(request.getParameter("tipo_expediente")));
            Part ficheiro = request.getPart("ficheiro");
            if (ficheiro != null) {
                byte[] ficheiroDados = IOUtils.toByteArray(ficheiro.getInputStream());
                documento.setConteudoDocumento(ficheiroDados);
                documento.setUrlFicheiroDocumento(ficheiro.getSubmittedFileName());
                doUpload(ficheiro, request);
            }

            documentoDAO.update(documento);
            response.sendRedirect("paginas/gerir_documento.jsp");

        } else if (comando.equalsIgnoreCase("eliminar")) {
            documentoDAO.delete(documento);
            response.sendRedirect("paginas/gerir_documento.jsp");

        } else if (comando.equalsIgnoreCase("prepara_editar")) {
            documento = documentoDAO.findById(documento.getNumeroProtocolo());
            request.setAttribute("documento", documento);

            RequestDispatcher rd = request.getRequestDispatcher("paginas/documento_editar.jsp");
            rd.forward(request, response);
        } else if (comando.equalsIgnoreCase("listar")) {

            response.sendRedirect("paginas/gerir_documento.jsp");
        } else if (comando.equalsIgnoreCase("imprimir_todos") || comando.equalsIgnoreCase("imprimir_by_id")) {
            ReporteUtil reporte = new ReporteUtil();
            File caminhoRelatorio = null;
            HashMap hashMap = new HashMap();

            if (comando.equalsIgnoreCase("imprimir_todos")) {
                caminhoRelatorio = new File(getServletConfig().getServletContext()
                        .getRealPath("/WEB-INF/relatorios/DocumentoListar.jasper"));
                reporte.geraRelatorio(caminhoRelatorio.getPath(), hashMap, response);
            } else {
                hashMap.put("codigo_documento", Integer.parseInt(idDocumento));
                caminhoRelatorio = new File(getServletConfig().getServletContext()
                        .getRealPath("/WEB-INF/relatorios/Ficha_Documento.jasper"));
                reporte.geraRelatorio(caminhoRelatorio.getPath(), hashMap, response);
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:AddPost.java

/**
 * metodo usato per gestire il caso di upload di file multipli da 
 * parte del'utente su un singolo post, siccome la libreria 
 * utilizzata non gestiva questo particolare caso.
 * @throws IOException/*from ww  w .  j  a  v a 2 s . c o  m*/
 * @throws ServletException
 * @throws SQLException 
 */
private void getFiles() throws IOException, ServletException, SQLException {
    Collection<Part> p = mReq.getParts();
    for (Part part : p) {
        if (part.getName().equals("post")) {
            //
        } else {
            if (part.getSize() > 1024 * 1024 * 10) {
                error++;
            } else {
                String path = mReq.getServletContext().getRealPath("/");
                String name = part.getSubmittedFileName();
                int i;
                if (isInGroupFiles(name)) {
                    for (i = 1; isInGroupFiles("(" + i + ")" + name); i++)
                        ;
                    name = "(" + i + ")" + name;
                }

                //Hotfixies for absoluth paths

                //IE
                if (name.contains("\\")) {
                    name = name.substring(name.lastIndexOf("\\"));
                }

                //somthing else, never encountered
                if (name.contains("/")) {
                    name = name.substring(name.lastIndexOf("/"));
                }

                dbm.newFile(dbm.getIdFromUser(user), groupid, name);

                File outputFile = new File(path + "/files/" + groupid + "/" + name);
                if (!outputFile.exists()) {
                    outputFile.createNewFile();
                }
                if (!outputFile.isDirectory()) {
                    InputStream finput = new BufferedInputStream(part.getInputStream());
                    OutputStream foutput = new BufferedOutputStream(new FileOutputStream(outputFile));

                    byte[] buffer = new byte[1024 * 500];
                    int bytes_letti = 0;
                    while ((bytes_letti = finput.read(buffer)) > 0) {
                        foutput.write(buffer, 0, bytes_letti);
                    }
                    finput.close();
                    foutput.close();
                }
            }
        }

    }

}

From source file:controllerClasses.StudyController.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* ww  w.  j  a  v  a  2s  . c o  m*/
 *
 * @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 {
    System.out.println("In StudyController");
    HttpSession session = null;
    //String action = request.getParameter("action");
    String userPath = request.getServletPath().substring(1, request.getServletPath().length());
    RequestDispatcher dispatcher = null;
    String reDirect = null;
    String studyCode = null;
    String choice = null;
    StudyDB studyDB = null;
    List<Study> studies = null;
    User user = null;

    try {
        HttpSession session2 = request.getSession();
        String email = (String) session2.getAttribute("email");
        session = request.getSession(false);
        if (session != null && session.getAttribute("theUser") != null) {
            user = (User) session.getAttribute("theUser");
            studyDB = new StudyDB();
            if (userPath.equals("participate")) {
                studyCode = request.getParameter("studyCode");
                String email1 = (String) session2.getAttribute("email");

                System.out.println("user email in study controller from session" + email1);
                if (studyCode != null && !studyCode.isEmpty()) {
                    System.out.println("studyCode in first block:  " + studyCode);
                    Study study = studyDB.getStudy(studyCode);
                    request.setAttribute("study", study);
                    reDirect = "question";
                } else {

                    List result = StudyDB.retrieveStudies1(email);
                    Study study = new Study();

                    String s = study.getName();
                    System.out.println("Controller study object" + s);

                    request.setAttribute("study", study);
                    request.setAttribute("result", result);
                    reDirect = "participate";
                }
            } else if (userPath.equals("answer")) {
                studyCode = request.getParameter("studyCode");
                choice = request.getParameter("choice");
                System.out.println("studyCode: " + studyCode);
                System.out.println("choice: " + choice);

                List result = StudyDB.answer(email, choice, studyCode);

                int i = UserDB.updateParticipations(email);
                user.setParticipation(i);
                int j = UserDB.updateCoins(email);
                user.setCoins(j);
                int k = UserDB.updateParticipants(email, studyCode);
                user.setParticipants(k);
                int participants = UserDB.getAttribute(email);
                int coins = UserDB.coins(email);
                int participation = UserDB.participation(email);

                user.setParticipants(participants);
                user.setCoins(coins);
                user.setParticipation(participation);

                request.setAttribute("user", user);

                /**
                List result = studyDB.getStudies();
                List<Study> sInStart = new ArrayList<Study>();
                for(Study study: studies){
                   if(study.getStatus().equalsIgnoreCase("start")){
                      sInStart.add(study);
                   }
                }
                System.out.println(sInStart.size());**/
                session.setAttribute("theUser", user);
                request.setAttribute("openStudies", result);
                request.setAttribute("result", result);

                reDirect = "participate";
            } else if (userPath.equals("myStudies")) {
                List result = studyDB.retrieveStudies(email);
                Study study = new Study();
                request.setAttribute("study", study);
                request.setAttribute("result", result);
                session.setAttribute("result", result);
                session.setAttribute("myStudies", studies);
                reDirect = "studies";
            } else if (userPath.equals("edit")) {
                studyCode = request.getParameter("studyCode");
                String email3 = (String) session2.getAttribute("email");

                Study study = new Study();
                study = StudyDB.getStudy(studyCode);
                /**
                if(session.getAttribute("myStudies")!=null){
                studies = (List<Study>) session.getAttribute("myStudies");
                }else{
                studies = studyDB.getStudies(user.getEmail());
                }
                for(Study study: studies){
                if(study.getCode() == Integer.parseInt(studyCode)){
                request.setAttribute("study", studyDB.getStudy(Integer.parseInt(studyCode)));
                break;
                }
                }**/
                request.setAttribute("study", study);
                reDirect = "editstudy";
                /*Pending*/
            } else if (userPath.equals("update")) {
                studyCode = request.getParameter("studyCode");
                Study study = new Study();
                study.setCode(Integer.parseInt(request.getParameter("studyCode")));
                study.setName(request.getParameter("studyName"));
                study.setQuestion(request.getParameter("questionText"));
                study.setRequestedParticipants(Integer.parseInt(request.getParameter("participants")));
                study.setDescription(request.getParameter("description"));
                Part part = request.getPart("imageFile");
                String fileName = part.getSubmittedFileName();
                String file1 = "images/" + fileName;
                study.setImageURL(file1);

                System.out.println("IMAGE NAME" + file1);
                System.out.println("IMAGE NAME FROM STUDY OBJECT" + study.getImageURL());

                List result = StudyDB.updateStudy(study, email);
                /**
                if(session.getAttribute("myStudies")!=null){
                studies = (List<Study>) session.getAttribute("myStudies");
                }else{
                studies = studyDB.getStudies(user.getEmail());
                }
                for(Study study: studies){
                if(study.getCode() == Integer.parseInt(studyCode)){
                studies.remove(study);
                study.setCode(Integer.parseInt(request.getParameter("studyCode")));
                study.setName(request.getParameter("studyName"));
                study.setQuestion(request.getParameter("questionText"));
                study.setRequestedParticipants(Integer.parseInt(request.getParameter("participants")));
                study.setDescription(request.getParameter("description"));
                        
                studies.add(study);
                break;
                }
                }**/
                request.setAttribute("result", result);
                request.setAttribute("study", study);
                session.setAttribute("myStudies", studies);
                reDirect = "studies";
            } else if (userPath.equals("add")) {

                Study study = new Study();
                study.setCode((int) Math.random());
                study.setName(request.getParameter("studyName"));
                study.setQuestion(request.getParameter("questionText"));
                study.setRequestedParticipants(Integer.parseInt(request.getParameter("participants")));

                study.setDescription(request.getParameter("description"));
                Part part = request.getPart("imageFile");
                String fileName = part.getSubmittedFileName();
                String file1 = "images/" + fileName;
                study.setImageURL(file1);
                /**
                studies = (List<Study>) session.getAttribute("myStudies");
                studies.add(study);**/
                List result1 = StudyDB.addStudy(study, email);

                List result = StudyDB.retrieveStudies(email);
                Study study1 = new Study();
                request.setAttribute("result", result);

                session.setAttribute("myStudies", studies);
                reDirect = "studies";
            } else if (userPath.equals("start")) {
                studyCode = request.getParameter("studyCode");

                List result = StudyDB.startStudy(studyCode, email);
                Study study = new Study();
                session.setAttribute("result", result);
                study.setStatus("started");
                session.setAttribute("choice", "started");
                /**
                if(session.getAttribute("myStudies")!=null){
                studies = (List<Study>) session.getAttribute("myStudies");
                }
                for(Study study: studies){
                if(study.getCode() == Integer.parseInt(studyCode)){
                studies.remove(study);
                study.setStatus("start");
                studies.add(study);
                System.out.println("studyCode:  " + studyCode);
                System.out.println("New Status:  " + study.getStatus());
                break;
                }
                }**/
                session.setAttribute("myStudies", studies);
                reDirect = "studies";
            } else if (userPath.equals("stop")) {
                studyCode = request.getParameter("studyCode");

                System.out.println("study code from DB" + studyCode);
                List result = StudyDB.stopStudy(studyCode, email);
                Study study = new Study();
                study.setStatus("stopped");
                session.setAttribute("result", result);

                System.out.println("studyCode:  " + studyCode);
                /**
                if(session.getAttribute("myStudies")!=null){
                studies = (List<Study>) session.getAttribute("myStudies");
                }
                for(Study study1: studies){
                if(study1.getCode() == Integer.parseInt(studyCode)){
                studies.remove(study);
                study1.setStatus(null);
                studies.add(study);
                System.out.println("studyCode:  " + studyCode);
                System.out.println("New Status:  " + study.getStatus());
                break;
                }
                }**/
                session.setAttribute("myStudies", studies);
                reDirect = "studies";
            }
            dispatcher = getServletContext().getRequestDispatcher("/" + reDirect + ".jsp");
            dispatcher.forward(request, response);
        } else {
            dispatcher = getServletContext().getRequestDispatcher("/" + "login" + ".jsp");
            dispatcher.forward(request, response);
        }
    } catch (Exception e) {
        e.printStackTrace();
        dispatcher = getServletContext().getRequestDispatcher("/main.jsp");
        dispatcher.forward(request, response);
    }

}

From source file:de.teamgrit.grit.webserver.ConnectionHandler.java

/**
 * Action to create a new connection./*from   ww  w .  j a v  a2s . co m*/
 *
 * @param request
 *            the {@link HttpServletRequest} passed to the handle() method
 * @return the added {@link Connection} on success, null otherwise
 * @throws BadRequestException
 *             if something goes wrong due to a bad request
 * @throws InternalActionErrorException
 *             if something else goes wrong (e.g. could not write to file)
 */
private String create(HttpServletRequest request) throws BadRequestException, InternalActionErrorException {
    String errorPrefix = "Error in connection/create:\n";

    /* Get all needed parameters from the request. */
    String connectionName;
    ConnectionType connectionType;
    String location;
    String username;
    String password;
    String sshUsername;
    List<String> structure;
    try {
        connectionName = parseName(request.getParameter("connectionName"), "connection name");
        connectionType = parseConnectionType(request.getParameter("connectionType"));
        location = parseLocation(request.getParameter("location"));
        username = parseName(request.getParameter("username"), "username");
        password = request.getParameter("password");
        if (connectionType == ConnectionType.ILIAS) {
            sshUsername = parseName(request.getParameter("sshUsername"), "sshUsername");
        } else {
            sshUsername = "";
        }
        if (connectionType == ConnectionType.SVN) {
            structure = parseStructure(request.getParameter("structure"));
        } else {
            structure = null;
        }
    } catch (BadRequestException e) {
        throw new BadRequestException(errorPrefix + e.getMessage());
    }

    /* If this is an ILIAS connection, we need the SSH key-file */
    Part sshKey = null;
    String keyFileName = "";
    if (connectionType == ConnectionType.ILIAS) {
        try {
            sshKey = request.getPart("sshKeyFile");

        } catch (ServletException e) {
            throw new BadRequestException(errorPrefix + "No multipart request.");
        } catch (IOException e) {
            throw new InternalActionErrorException(errorPrefix + "Could not read the submitted keyfile.");
        }
        keyFileName = sshKey.getSubmittedFileName();
        if ((keyFileName == null) || ("".equals(keyFileName))) {
            throw new BadRequestException("No key-file submitted!");
        }
    }

    /* Create the connection. */
    Connection connection = null;
    try {
        connection = m_controller.addConnection(connectionName, connectionType, location, username, password,
                sshUsername, keyFileName, structure);
    } catch (ConfigurationException e) {
        throw new InternalActionErrorException(errorPrefix + "Could not create connection.");
    } catch (InvalidStructureException e) {
        throw new InternalActionErrorException(errorPrefix + "The submitted structure is invalid.");
    }

    /* Write the key-file if this is an ILIAS connection. */
    if (connectionType == ConnectionType.ILIAS) {
        Path outputDirectory = connection.getSshKeyFileLocation().getParent();
        writeSubmittedFile(sshKey, outputDirectory);
    }

    return GSON.toJson(connection);
}

From source file:de.teamgrit.grit.webserver.ConnectionHandler.java

/**
 * Action to update a connection.//w w  w . ja  va 2 s. c  om
 *
 * @param connectionId
 *            the ID of the connection
 * @param request
 *            the {@link HttpServletRequest} passed to the handle() method
 * @return the added {@link Connection} on success, null otherwise
 * @throws BadRequestException
 *             if something goes wrong due to a bad request
 * @throws InternalActionErrorException
 *             if something else goes wrong (e.g. could not write to file)
 */
private String update(String connectionId, HttpServletRequest request)
        throws BadRequestException, InternalActionErrorException {
    String errorPrefix = "Error in connection/create:\n";

    /* Get all needed parameters from the request. */
    String connectionName;
    ConnectionType connectionType;
    String location;
    String username;
    String password;
    String sshUsername;
    List<String> structure;
    try {
        connectionName = parseName(request.getParameter("connectionName"), "connection name");
        connectionType = parseConnectionType(request.getParameter("connectionType"));
        location = parseLocation(request.getParameter("location"));
        username = parseName(request.getParameter("username"), "username");
        password = request.getParameter("password");
        if (connectionType == ConnectionType.ILIAS) {
            sshUsername = parseName(request.getParameter("sshUsername"), "sshUsername");
        } else {
            sshUsername = "";
        }
        if (connectionType == ConnectionType.SVN) {
            structure = parseStructure(request.getParameter("structure"));
        } else {
            structure = null;
        }
    } catch (BadRequestException e) {
        throw new BadRequestException(errorPrefix + e.getMessage());
    }

    /* If this is an ILIAS connection, we need the SSH key-file */
    Part sshKey = null;
    String keyFileName = "";
    if (connectionType == ConnectionType.ILIAS) {
        try {
            sshKey = request.getPart("sshKeyFile");
        } catch (ServletException e) {
            throw new BadRequestException(errorPrefix + "No multipart request.");
        } catch (IOException e) {
            throw new InternalActionErrorException(errorPrefix + "Could not read the submitted keyfile.");
        }
        keyFileName = sshKey.getSubmittedFileName();
        if ((keyFileName == null) || ("".equals(keyFileName))) {
            throw new BadRequestException("No key-file submitted!");
        }
    }

    int connectionIdInt = Integer.parseInt(connectionId);

    /* Update the connection. */
    Connection connection = null;
    try {
        connection = m_controller.updateConnection(connectionIdInt, connectionName, connectionType, location,
                username, password, sshUsername, keyFileName, structure);
    } catch (ConfigurationException e) {
        throw new InternalActionErrorException(errorPrefix + "Could not create connection.");
    } catch (InvalidStructureException e) {
        throw new InternalActionErrorException(errorPrefix + "The submitted structure is invalid.");
    }

    /* Write the key-file if this is an ILIAS connection. */
    if (connectionType == ConnectionType.ILIAS) {
        Path outputDirectory = connection.getSshKeyFileLocation().getParent();
        writeSubmittedFile(sshKey, outputDirectory);
    }

    return GSON.toJson(connection);
}

From source file:com.spring.tutorial.entitites.FileUploader.java

public String upload() throws IOException, ServletException, FacebookException {
    OutputStream output = null;/*from  w  w w .  j  a  v  a 2 s .  com*/
    InputStream fileContent = null;
    final Part filePart;

    final File file;
    try {
        filePart = request.getPart("file");

        fileContent = filePart.getInputStream();

        MongoClient mongoClient = new MongoClient();
        mongoClient = new MongoClient();
        DB db = mongoClient.getDB("fou");

        char[] pass = "mongo".toCharArray();
        boolean auth = db.authenticate("admin", pass);

        file = File.createTempFile("fileToStore", "tmp");

        file.deleteOnExit();
        FileOutputStream fout = new FileOutputStream(file);

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

        while ((read = fileContent.read(bytes)) != -1) {
            fout.write(bytes, 0, read);
        }

        GridFS gridFS = new GridFS(db, request.getSession().getAttribute("id") + "_files");
        GridFSInputFile gfsInputFile = gridFS.createFile(file);
        gfsInputFile.setFilename(filePart.getSubmittedFileName());
        gfsInputFile.save();

        DBCollection collection = db.getCollection(request.getSession().getAttribute("id") + "_files_meta");
        BasicDBObject metaDocument = new BasicDBObject();
        metaDocument.append("name", filePart.getSubmittedFileName());
        metaDocument.append("size", filePart.getSize());
        metaDocument.append("content-type", filePart.getContentType());
        metaDocument.append("file-id", gfsInputFile.getId());
        metaDocument.append("tags", request.getParameter("tags"));
        metaDocument.append("description", request.getParameter("description"));

        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        metaDocument.append("last_modified", dateFormat.format(new Date()));

        collection.insert(metaDocument);

    } catch (Exception e) {
        return "message:" + e.getMessage();
    } finally {
        if (output != null) {
            output.close();
        }
        if (fileContent != null) {
            fileContent.close();
        }
    }

    return "success";
}

From source file:de.dentrassi.pm.storage.web.channel.ChannelController.java

@RequestMapping(value = "/channel/{channelId}/add", method = RequestMethod.POST)
public ModelAndView addPost(@PathVariable("channelId") final String channelId,
        @RequestParameter(required = false, value = "name") String name,
        final @RequestParameter("file") Part file) {
    try {//  w  w  w .  j  ava2 s .c o m
        if (name == null || name.isEmpty()) {
            name = file.getSubmittedFileName();
        }

        final String finalName = name;

        this.channelService.access(By.id(channelId), ModifiableChannel.class, channel -> {
            channel.getContext().createArtifact(file.getInputStream(), finalName, null);
        });

        // FIXME: this.service.createArtifact ( channelId, name, file.getInputStream (), null );

        return redirectDefaultView(channelId, true);
    } catch (final Exception e) {
        return CommonController.createError("Upload", "Upload failed", e);
    }
}

From source file:de.dentrassi.pm.storage.web.channel.ChannelController.java

@RequestMapping(value = "/channel/{channelId}/drop", method = RequestMethod.POST)
public void drop(@PathVariable("channelId") final String channelId,
        @RequestParameter(required = false, value = "name") String name,
        final @RequestParameter("file") Part file, final HttpServletResponse response) throws IOException {
    response.setContentType("text/plain");

    try {//w w w  .ja v  a  2  s . c o  m
        if (name == null || name.isEmpty()) {
            name = file.getSubmittedFileName();
        }

        final String finalName = name;

        this.channelService.access(By.id(channelId), ModifiableChannel.class, channel -> {
            channel.getContext().createArtifact(file.getInputStream(), finalName, null);
        });

        // FIXME: this.service.createArtifact ( channelId, name, file.getInputStream (), null );
    } catch (final Throwable e) {
        logger.debug("Failed to drop file", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write("Internal error: " + ExceptionHelper.getMessage(e));
        return;
    }

    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().write("OK");
}