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:com.playright.servlet.DataController.java

private static CoverageData getCoverageDateFromRequest(HttpServletRequest request) throws ServletException {
    CoverageData cd = new CoverageData();
    try {/* w ww.  j  a v  a 2 s.com*/
        if (!"".equalsIgnoreCase(request.getParameter("id")) && request.getParameter("id") != null) {
            cd.setId(Integer.parseInt(request.getParameter("id")));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        java.util.Date ud = sdf.parse(request.getParameter("newsDate"));
        cd.setNewsDate(new java.sql.Date(ud.getTime()));
        cd.setNewspaper(request.getParameter("newspaper"));
        cd.setHeadline(request.getParameter("headline"));
        cd.setLanguage(request.getParameter("language"));
        cd.setEdition(request.getParameter("edition"));
        cd.setSupplement(request.getParameter("supplement"));
        cd.setSource(request.getParameter("source"));
        if (!"".equalsIgnoreCase(request.getParameter("pageNo")) && request.getParameter("pageNo") != null) {
            cd.setPageNo(Integer.parseInt(request.getParameter("pageNo")));
        }
        if (!"".equalsIgnoreCase(request.getParameter("height")) && request.getParameter("height") != null) {
            cd.setHeight(Integer.parseInt(request.getParameter("height")));
        }
        if (!"".equalsIgnoreCase(request.getParameter("width")) && request.getParameter("width") != null) {
            cd.setWidth(Integer.parseInt(request.getParameter("width")));
        }
        if (!"".equalsIgnoreCase(request.getParameter("totalArticleSize"))
                && request.getParameter("totalArticleSize") != null) {
            cd.setTotalArticleSize(Integer.parseInt(request.getParameter("totalArticleSize")));
        }
        if (!"".equalsIgnoreCase(request.getParameter("circulationFigure"))
                && request.getParameter("circulationFigure") != null) {
            cd.setCirculationFigure(Integer.parseInt(request.getParameter("circulationFigure")));
        }
        if (!"".equalsIgnoreCase(request.getParameter("journalistFactor"))
                && request.getParameter("journalistFactor") != null) {
            cd.setJournalistFactor(Integer.parseInt(request.getParameter("journalistFactor")));
        }
        if (!"".equalsIgnoreCase(request.getParameter("quantitativeAve"))
                && request.getParameter("quantitativeAve") != null) {
            cd.setQuantitativeAve(new BigDecimal(request.getParameter("quantitativeAve")));
        }
        if (!"".equalsIgnoreCase(request.getParameter("imageExists"))
                && request.getParameter("imageExists") != null) {
            cd.setImageExists(request.getParameter("imageExists"));
        }
        Blob b = null;
        String fileName = "";
        String contentType = "";
        try {
            Part filePart = request.getPart("image");
            InputStream fileContent = filePart.getInputStream();
            byte[] bytes = IOUtils.toByteArray(fileContent);
            b = new SerialBlob(bytes);
            fileName = filePart.getSubmittedFileName();
            contentType = filePart.getContentType();
        } catch (IOException ex) {
            Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (b != null && b.length() != 0) {
            cd.setImageBlob(b);
            cd.setImageFileName(fileName);
            cd.setImageType(contentType);
        }
    } catch (ParseException ex) {
        Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return cd;
}

From source file:rzd.vivc.documentexamination.service.FileSavingToDiskService.java

@Override
public void saveUploadedFile(DocumentForm document) throws IOException {
    Part file = document.getFile();

    if (file == null || file.getSize() < 0 || file.getSubmittedFileName().isEmpty()) {
        //?    ,  ? ? ? 
    } else {/*from  w  ww .  ja  v  a  2s  .c om*/
        String address = "C:" + File.separator + File.separator + "documents" + File.separator;
        String name = file.getSubmittedFileName();
        while ((new File(address + name)).exists()) {
            String[] split = name.split("\\.");
            name = split[split.length - 2] + UUID.randomUUID().toString() + "." + split[split.length - 1];
        }
        file.write(address + name);
        document.setFileName(name);
    }
}

From source file:br.edu.ifpb.sislivros.actions.CadastrarLivro.java

private Livro montarLivro(HttpServletRequest request)
        throws FileUploadException, IOException, ServletException {
    Livro livro = new Livro();

    //processando e salvando a capa do livro
    Part capaPart = request.getPart("capa");
    String nomeArquivo = capaPart.getSubmittedFileName();
    if (nomeArquivo == null || nomeArquivo == "")
        nomeArquivo = "img/livros/capa_default.png";
    String isbn = request.getParameter("isbn");
    String capa = new ProcessadorFotos("img/livros").processarArquivoCapa(request, capaPart,
            "capa" + isbn + nomeArquivo);
    livro.setCapa(capa);/*  w w w  .jav  a 2  s  .c  o  m*/

    int ano = Integer.parseInt(request.getParameter("anoPublicacao"));
    livro.setAnoPublicacao(ano);
    livro.setAreaTema(request.getParameter("areaTema"));
    livro.setAutores(request.getParameter("autores"));
    livro.setEditora(request.getParameter("editora"));
    livro.setIsbn(isbn);
    livro.setTitulo(request.getParameter("titulo"));

    return livro;
}

From source file:it.unitn.elisco.servlet.ImageUploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w ww .  j av  a2s .  com
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession(false);
    Person user;

    if (request.getRequestURI().equals("/admin/image_upload")) {
        user = (Person) session.getAttribute("admin");
    } else {
        user = (Person) session.getAttribute("student");
    }
    // Get the image uploaded by the user as a stream
    Part imagePart = request.getPart("image");
    String imageExtension = "." + imagePart.getSubmittedFileName().split("\\.")[1];

    // Write to a temp file
    File tempFile = File.createTempFile("tmp", imageExtension);
    tempFile.deleteOnExit();
    FileOutputStream out = new FileOutputStream(tempFile);
    IOUtils.copy(imagePart.getInputStream(), out);

    // Upload the image to Cloudinary
    ImageUploader uploader = ImageUploader.getInstance();
    String imageId = uploader.uploadImageToCloud(user, tempFile);

    // Get the url for the uploaded image
    String imageUrl = uploader.getURLWithDimensions(imageId, 200, 200);

    // Send JSON response back to ajax
    String json = new Gson().toJson(imageUrl);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

From source file:Service.FichierServiceImpl.java

private boolean ajoutFichierInterne(Part p, String nom) throws IOException {
    String s = "";
    if (!"".equals(p.getSubmittedFileName())) {
        s += "bonjour";
        String separator = System.getProperty("file.separator");
        File f = new File(servletContext.getRealPath("/WEB-INF/files") + separator);
        File fdef = new File(f.getParentFile().getParentFile().getParentFile().getParentFile().getAbsolutePath()
                + separator + "web" + separator + "files" + separator + nom);

        fdef.delete();//from www .  j  a  v a 2 s .  c o  m
        fdef.createNewFile();
        try {
            s += "[[[[" + fdef.getAbsolutePath() + "]]]";
            InputStream in = p.getInputStream();
            OutputStream out = new FileOutputStream(fdef);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.close();

        } catch (Exception e) {
            return false;
        }
        return true;
    }
    return false;
}

From source file:es.uma.inftel.blog.servlet.PerfilServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w ww. j ava  2  s.  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 {

    request.setCharacterEncoding("UTF-8");

    BaseView baseView = new BaseView();
    BaseViewFacade<BaseView> baseViewFacade = new BaseViewFacade<>(postFacade);
    baseViewFacade.initView(baseView);

    RequestDispatcher requestDispatcher = request.getRequestDispatcher("perfil.jsp");
    String password = request.getParameter("password");
    if (password == null) {
        request.setAttribute("perfilView", baseView);
        requestDispatcher.forward(request, response);
    }

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

    Part filePart = request.getPart("avatar");
    byte[] avatar = null;
    if (!filePart.getSubmittedFileName().isEmpty()) {
        InputStream inputStream = filePart.getInputStream();
        avatar = IOUtils.toByteArray(inputStream);
    }

    HttpSession session = request.getSession();
    Usuario usuario = (Usuario) session.getAttribute("usuario");

    modificarUsuario(usuario, password, email, avatar);
    response.sendRedirect("perfil");

}

From source file:Service.FichierServiceImpl.java

@Override
public boolean ajoutFichier(Part p, int statutsId) {

    StatutsEntity se = statutsDAO.find(statutsId);
    String nouveauNom = hashNomFichier(se.getAuteur().getLogin() + p.getSubmittedFileName());
    String[] split = p.getSubmittedFileName().split("\\.");
    String ext = split[split.length - 1];
    nouveauNom += "." + ext;

    for (FichiersEntity fe : se.getListeFichiers()) {
        if (fe.getNom().equals(nouveauNom)) {
            return false;
        }// w  w  w .ja va 2 s .c  om
    }
    try {
        ajoutFichierInterne(p, nouveauNom);
    } catch (IOException ex) {
        Logger.getLogger(FichierServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    FichiersEntity fe = new FichiersEntity(ext, p.getSubmittedFileName(), nouveauNom);

    statutsDAO.addFichier(se, fe);
    return true;
}

From source file:com.matrimony.controller.ProfileController.java

@RequestMapping(value = "changeAvatar", method = RequestMethod.POST)
public String doChangeAvatar(HttpServletRequest request) {
    User ssUser = (User) request.getSession().getAttribute(SessionKey.USER);
    if (ssUser == null)
        return "joinUs";
    try {//from  w  w  w.j  a  v  a2 s . c om
        Collection<Part> parts = request.getParts();
        for (Part p : parts) {
            String originName = p.getSubmittedFileName();
            if (originName != null) {
                System.out.println(originName);
                String[] extensionFile = originName.split("\\.");
                if (extensionFile.length > 1) {
                    String avatarFolderPath = request.getServletContext()
                            .getRealPath("/resources/profile/avatar");
                    System.out.println("avatar folder: " + avatarFolderPath);

                    // MAKE OBF NAME AVATAR IMAGE
                    String obfName = RandomStringUtils.randomAlphanumeric(26);
                    StringBuilder filePath = new StringBuilder(avatarFolderPath);
                    filePath.append("/");
                    filePath.append(obfName);
                    filePath.append(".");
                    filePath.append(extensionFile[1]);

                    UploadImageToServer upload = new UploadImageToServer();
                    upload.upload(filePath.toString(), p.getInputStream());
                    System.out.println("Uploaded " + filePath.toString());
                    // UPDATE AVATAR
                    UserDAO.Update(ssUser);
                    ssUser.setAvatarPhoto(obfName + "." + extensionFile[1]);
                    return "redirect:";
                }
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ServletException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return "profile";
}

From source file:es.uma.inftel.blog.servlet.PostServlet.java

private void insertarImagen(HttpServletRequest request, Post idPost) throws ServletException, IOException {
    int numeroFotos, i;
    numeroFotos = Integer.parseInt(request.getParameter("numFotos"));
    for (i = 0; i < numeroFotos + 1; i++) {
        Part filePart = request.getPart("foto-" + i);
        if (filePart != null) {
            if (!filePart.getSubmittedFileName().isEmpty()) {
                Imagen imagen = new Imagen();
                InputStream inputStream = filePart.getInputStream();
                byte[] foto = IOUtils.toByteArray(inputStream);
                imagen.setPostId(idPost);
                imagen.setFoto(foto);/*  w  w  w .ja  v  a 2s  .c  o  m*/
                imagenFacade.create(imagen);
            }
        }
    }

}

From source file:com.ge.apm.service.asset.AttachmentFileService.java

public Integer uploadFile(Part file) {
    Integer returnId = 0;/*w ww .  j a va 2 s . c  om*/
    try {
        returnId = fileUploaddao.saveUploadFile(file.getInputStream(),
                Integer.valueOf(String.valueOf(file.getSize())), file.getSubmittedFileName());
    } catch (SQLException | IOException ex) {
        WebUtil.addErrorMessage(WebUtil.getMessage("fileTransFail"));
        Logger.getLogger(AttachmentFileService.class.getName()).log(Level.SEVERE, null, ex);
    }
    return returnId;
}