显示上传的图像404错误

时间:2013-09-05 17:33:07

标签: forms servlets file-upload download

我正在尝试使用InscriptionForm.java从注册表单上传图像以检查尊重字段。上传没有问题(感谢BalusC的教程),但是,当我尝试显示上传的图像时,我不能;参考HTTP网络监视器我得到 404错误作为响应。此外,当我尝试将上述链接输入浏览器的地址栏http://localhost:8080/projetForum/images/bd/Id_21082013184506.png时,我遇到了404错误。

InscriptionForm.java

public final class InscriptionForm {
    private static final String CHAMP_EMAIL = "email";
    private static final String CHAMP_PASS = "motdepasse";
    private static final String CHAMP_CONF = "confirmation";
    private static final String CHAMP_NOM = "nom";
    private static final String CHAMP_DESC = "description";
    private static final String CHAMP_LOC = "localisation";
    private static final String CHAMP_SW = "siteweb";
    public static final String CHAMP_IMAGE = "avatar";
    public static final String CHAMP_JOURDENAISS = "jourdenaissance";
    public static final String CHAMP_MOISDENAISS = "moisdenaissance";
    public static final String CHAMP_ANNEEDENAISS = "anneedenaissance";
    public static final String CHAMP_DATEDENAISS = "datedenaissance";
    public static final int TAILLE_TAMPON = 10240; // 10 ko
    public static final String CHEMIN = "E:\\Bibliothèque logicielle\\workspace\\projetForum\\WebContent\\images\\bd\\";

    private String resultat;
    private static Map<String, String> erreurs = new HashMap<String, String>();

    public String getResultat() {
        return resultat;
    }

    public Map<String, String> getErreurs() {
        return erreurs;
    }

    public Utilisateur inscrireUtilisateur(HttpServletRequest request) {
        String email = getValeurChamp(request, CHAMP_EMAIL);
        String motDePasse = getValeurChamp(request, CHAMP_PASS);
        String confirmation = getValeurChamp(request, CHAMP_CONF);
        String nom = getValeurChamp(request, CHAMP_NOM);
        String description = getValeurChamp(request, CHAMP_DESC);
        String localisation = getValeurChamp(request, CHAMP_LOC);
        String siteweb = getValeurChamp(request, CHAMP_SW);
        String image = getValeurChamp(request, CHAMP_IMAGE);
        String jourdenaissance = getValeurChamp(request, CHAMP_JOURDENAISS);
        String moisdenaissance = getValeurChamp(request, CHAMP_MOISDENAISS);
        String anneedenaissance = getValeurChamp(request, CHAMP_ANNEEDENAISS);
        Integer datedenaissance = null;

        try {
            validationEmail(email);
        } catch (Exception e) {
            setErreur(CHAMP_EMAIL, e.getMessage());
        }

        try {
            validationMotsDePasse(motDePasse, confirmation);
        } catch (Exception e) {
            setErreur(CHAMP_PASS, e.getMessage());
        }

        try {
            validationNom(nom);
        } catch (Exception e) {
            setErreur(CHAMP_NOM, e.getMessage());
        }

        try {
            image = validationImage(request, CHEMIN);
        } catch (Exception e) {
            setErreur(CHAMP_IMAGE, e.getMessage());
        }

        if (!jourdenaissance.equals("defaut")
                && !moisdenaissance.equals("defaut")
                && !anneedenaissance.equals("defaut")) {
            try {
                validationDateDeNaiss(Integer.parseInt(jourdenaissance),
                        Integer.parseInt(moisdenaissance),
                        Integer.parseInt(anneedenaissance));
            } catch (Exception e) {
                setErreur(CHAMP_DATEDENAISS, e.getMessage());
            }
            datedenaissance = Integer.parseInt((jourdenaissance + ""
                    + moisdenaissance + "" + anneedenaissance));
        }
        if (jourdenaissance.equals("defaut")
                && moisdenaissance.equals("defaut")
                && anneedenaissance.equals("defaut")) {
        } else {
            setErreur(CHAMP_DATEDENAISS,
                    "Merci de vérifier votre date de naissance.");
        }

        Utilisateur utilisateur = new Utilisateur(email, motDePasse, nom,
                localisation, siteweb, description, datedenaissance, image);

        if (erreurs.isEmpty()) {
            resultat = "Succès de l'inscription.";
            createORupdate(utilisateur, request);
        } else {
            resultat = "Échec de l'inscription.";
        }

        return utilisateur;
    }

    private String validationImage(HttpServletRequest request, String chemin)
            throws Exception {
        File uploadFilePath = new File(chemin);
        // Validate file.
        Object fileObject = request.getAttribute("avatar");
        if (fileObject == null) {
            // No file uploaded.
            throw new Exception("Please select file to upload.");
        } else if (fileObject instanceof FileUploadException) {
            // File upload is failed.
            FileUploadException fileUploadException = (FileUploadException) fileObject;
            throw new Exception(fileUploadException.getMessage());
        }

        // If there are no errors, proceed with writing file.

        FileItem fileItem = (FileItem) fileObject;

        // Get file name from uploaded file and trim path from it.
        // Some browsers (e.g. IE, Opera) also sends the path, which is
        // completely irrelevant.
        String fileName = FilenameUtils.getName(fileItem.getName());

        // Prepare filename prefix and suffix for an unique filename in upload
        // folder.
        String prefix = FilenameUtils.getBaseName(fileName) + "_";
        String suffix = "." + FilenameUtils.getExtension(fileName);

        File file = null;

        try {
            // Prepare unique local file based on file name of uploaded file.
            file = File.createTempFile(prefix, suffix, uploadFilePath);

            // Write uploaded file to local file.
            fileItem.write(file);

        } catch (Exception e) {
            // Can be thrown by uniqueFile() and FileItem#write().
            throw new Exception(e.getMessage());
        }

        return file.getName();
    }


    private void setErreur(String champ, String message) {
        erreurs.put(champ, message);
    }

    private static String getValeurChamp(HttpServletRequest request,
            String nomChamp) {
        String valeur = request.getParameter(nomChamp);
        if (valeur == null || valeur.trim().length() == 0) {
            return null;
        } else {
            return valeur;
        }
    }

    private static void createORupdate(Utilisateur u, HttpServletRequest request) {
        Session s = HibernateUtils.getSession();
        Transaction tx = s.beginTransaction();
        Query q = s
                .createQuery("from Utilisateur where Utilisateur_email = :email");
        q.setString("email", u.getEmail());
        Utilisateur userUpdt = (Utilisateur) q.uniqueResult();

        if (userUpdt != null) {
            userUpdt.setNom(u.getNom());
            userUpdt.setEmail(u.getEmail());
            userUpdt.setSiteweb(u.getSiteweb());
            userUpdt.setLocalisation(u.getLocalisation());
            userUpdt.setDescription(u.getDescription());
            s.update(userUpdt);
        } else {
            SimpleDateFormat formater = new SimpleDateFormat(
                    "dd-MM-yyyy hh:mm:ss");
            Date aujourdhui = new Date();
            u.setDateInscrit(formater.format(aujourdhui));
            s.persist(u);
        }

        tx.commit();
    }

    private void validationEmail(String email) throws Exception {
        UtilisateurDAO<Utilisateur, String> ud = new UtilisateurDAO<Utilisateur, String>();
        if (ud.findByID(email) != null)
            throw new Exception("Adresse mail déjà utilisée.");
        else if (email == null || ud.findByID(email) != null
                || !email.matches("([^.@]+)(\\.[^.@]+)*@([^.@]+\\.)+([^.@]+)")) {
            throw new Exception("Merci de saisir une adresse mail valide.");
        }
    }

    private void validationDateDeNaiss(Integer jj, Integer mm, Integer aaaa)
            throws Exception {
        switch (mm) {
        case 2:
            if (jj > 28 && ((aaaa / 4) % 100 == 0 && aaaa % 400 == 0))
                throw new Exception(
                        "Merci de vérifier votre date de naissance.");
            break;
        case 4:
            if (jj == 31)
                throw new Exception(
                        "Merci de vérifier votre date de naissance.");
            break;
        case 6:
            if (jj == 31)
                throw new Exception(
                        "Merci de vérifier votre date de naissance.");
            break;
        case 9:
            if (jj == 31)
                throw new Exception(
                        "Merci de vérifier votre date de naissance.");
            break;
        case 11:
            if (jj == 31)
                throw new Exception(
                        "Merci de vérifier votre date de naissance.");
            break;
        }
    }

    private void validationMotsDePasse(String motDePasse, String confirmation)
            throws Exception {
        if (motDePasse != null && confirmation != null) {
            if (!motDePasse.equals(confirmation)) {
                throw new Exception(
                        "Les mots de passe entrés sont différents, merci de les saisir à nouveau.");
            } else if (motDePasse.length() < 6) {
                throw new Exception(
                        "Les mots de passe doivent contenir au moins 6 caractères.");
            }
        } else {
            throw new Exception(
                    "Merci de saisir et confirmer votre mot de passe.");
        }
    }

    private static void validationNom(String nom) throws Exception {
        ConfigFDAO<ConfigF, Integer> cfd = new ConfigFDAO<ConfigF, Integer>();
        UtilisateurDAO<Utilisateur, String> ud = new UtilisateurDAO<Utilisateur, String>();
        if (ud.findByNom(nom) != null)
            throw new Exception("Nom d'utilisateur déjà utilisée.");
        else if (nom == null
                || nom.length() < cfd.findByID(0).getPseudominsize()
                || nom.length() > cfd.findByID(0).getPseudomaxsize()) {
            throw new Exception("Le nom d'utilisateur doit contenir au moins "
                    + cfd.findByID(0).getPseudominsize() + " et au maximum "
                    + cfd.findByID(0).getPseudomaxsize() + " caractères.");
        }
    }

    private static String getNomFichier(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim()
                        .replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1)
                        .substring(filename.lastIndexOf('\\') + 1);
            }
        }
        return null;
    }
}

MultipartFilter.java

public class MultipartFilter implements Filter {

    // Init
    // ---------------------------------------------------------------------------------------

    private long maxFileSize;

    // Actions
    // ------------------------------------------------------------------------------------

    /**
     * Configure the 'maxFileSize' parameter.
     * 
     * @throws ServletException
     *             If 'maxFileSize' parameter value is not numeric.
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    public void init(FilterConfig filterConfig) throws ServletException {
        // Configure maxFileSize.
        String maxFileSize = filterConfig.getInitParameter("maxFileSize");
        if (maxFileSize != null) {
            if (!maxFileSize.matches("^\\d+$")) {
                throw new ServletException(
                        "MultipartFilter 'maxFileSize' is not numeric.");
            }
            this.maxFileSize = Long.parseLong(maxFileSize);
        }
    }

    /**
     * Check the type request and if it is a HttpServletRequest, then parse the
     * request.
     * 
     * @throws ServletException
     *             If parsing of the given HttpServletRequest fails.
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
     *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws ServletException, IOException {
        // Check type request.
        if (request instanceof HttpServletRequest) {
            // Cast back to HttpServletRequest.
            HttpServletRequest httpRequest = (HttpServletRequest) request;

            // Parse HttpServletRequest.
            HttpServletRequest parsedRequest = parseRequest(httpRequest);

            // Continue with filter chain.
            chain.doFilter(parsedRequest, response);
        } else {
            // Not a HttpServletRequest.
            chain.doFilter(request, response);
        }
    }

    /**
     * @see javax.servlet.Filter#destroy()
     */
    public void destroy() {
        // I am a boring method.
    }

    // Helpers
    // ------------------------------------------------------------------------------------

    /**
     * Parse the given HttpServletRequest. If the request is a multipart
     * request, then all multipart request items will be processed, else the
     * request will be returned unchanged. During the processing of all
     * multipart request items, the name and value of each regular form field
     * will be added to the parameterMap of the HttpServletRequest. The name and
     * File object of each form file field will be added as attribute of the
     * given HttpServletRequest. If a FileUploadException has occurred when the
     * file size has exceeded the maximum file size, then the
     * FileUploadException will be added as attribute value instead of the
     * FileItem object.
     * 
     * @param request
     *            The HttpServletRequest to be checked and parsed as multipart
     *            request.
     * @return The parsed HttpServletRequest.
     * @throws ServletException
     *             If parsing of the given HttpServletRequest fails.
     */
    @SuppressWarnings("unchecked")
    // ServletFileUpload#parseRequest() does not return generic type.
    private HttpServletRequest parseRequest(HttpServletRequest request)
            throws ServletException {

        // Check if the request is actually a multipart/form-data request.
        if (!ServletFileUpload.isMultipartContent(request)) {
            // If not, then return the request unchanged.
            return request;
        }

        // Prepare the multipart request items.
        // I'd rather call the "FileItem" class "MultipartItem" instead or so.
        // What a stupid name ;)
        List<FileItem> multipartItems = null;

        try {
            // Parse the multipart request items.
            multipartItems = new ServletFileUpload(new DiskFileItemFactory())
                    .parseRequest(request);
            // Note: we could use ServletFileUpload#setFileSizeMax() here, but
            // that would throw a
            // FileUploadException immediately without processing the other
            // fields. So we're
            // checking the file size only if the items are already parsed. See
            // processFileField().
        } catch (FileUploadException e) {
            throw new ServletException("Cannot parse multipart request: "
                    + e.getMessage());
        }

        // Prepare the request parameter map.
        Map<String, String[]> parameterMap = new HashMap<String, String[]>();

        // Loop through multipart request items.
        for (FileItem multipartItem : multipartItems) {
            if (multipartItem.isFormField()) {
                // Process regular form field (input
                // type="text|radio|checkbox|etc", select, etc).
                processFormField(multipartItem, parameterMap);
            } else {
                // Process form file field (input type="file").
                processFileField(multipartItem, request);
            }
        }

        // Wrap the request with the parameter map which we just created and
        // return it.
        return wrapRequest(request, parameterMap);
    }

    /**
     * Process multipart request item as regular form field. The name and value
     * of each regular form field will be added to the given parameterMap.
     * 
     * @param formField
     *            The form field to be processed.
     * @param parameterMap
     *            The parameterMap to be used for the HttpServletRequest.
     */
    private void processFormField(FileItem formField,
            Map<String, String[]> parameterMap) {
        String name = formField.getFieldName();
        String value = formField.getString();
        String[] values = parameterMap.get(name);

        if (values == null) {
            // Not in parameter map yet, so add as new value.
            parameterMap.put(name, new String[] { value });
        } else {
            // Multiple field values, so add new value to existing array.
            int length = values.length;
            String[] newValues = new String[length + 1];
            System.arraycopy(values, 0, newValues, 0, length);
            newValues[length] = value;
            parameterMap.put(name, newValues);
        }
    }

    /**
     * Process multipart request item as file field. The name and FileItem
     * object of each file field will be added as attribute of the given
     * HttpServletRequest. If a FileUploadException has occurred when the file
     * size has exceeded the maximum file size, then the FileUploadException
     * will be added as attribute value instead of the FileItem object.
     * 
     * @param fileField
     *            The file field to be processed.
     * @param request
     *            The involved HttpServletRequest.
     */
    private void processFileField(FileItem fileField, HttpServletRequest request) {
        if (fileField.getName().length() <= 0) {
            // No file uploaded.
            request.setAttribute(fileField.getFieldName(), null);
        } else if (maxFileSize > 0 && fileField.getSize() > maxFileSize) {
            // File size exceeds maximum file size.
            request.setAttribute(fileField.getFieldName(),
                    new FileUploadException(
                            "File size exceeds maximum file size of "
                                    + maxFileSize + " bytes."));
            // Immediately delete temporary file to free up memory and/or disk
            // space.
            fileField.delete();
        } else {
            // File uploaded with good size.
            request.setAttribute(fileField.getFieldName(), fileField);
        }
    }

    // Utility (may be refactored to public utility class)
    // ----------------------------------------

    /**
     * Wrap the given HttpServletRequest with the given parameterMap.
     * 
     * @param request
     *            The HttpServletRequest of which the given parameterMap have to
     *            be wrapped in.
     * @param parameterMap
     *            The parameterMap to be wrapped in the given
     *            HttpServletRequest.
     * @return The HttpServletRequest with the parameterMap wrapped in.
     */
    private static HttpServletRequest wrapRequest(HttpServletRequest request,
            final Map<String, String[]> parameterMap) {
        return new HttpServletRequestWrapper(request) {
            public Map<String, String[]> getParameterMap() {
                return parameterMap;
            }

            public String[] getParameterValues(String name) {
                return parameterMap.get(name);
            }

            public String getParameter(String name) {
                String[] params = getParameterValues(name);
                return params != null && params.length > 0 ? params[0] : null;
            }

            public Enumeration<String> getParameterNames() {
                return Collections.enumeration(parameterMap.keySet());
            }
        };
    }

}

提前致谢。

0 个答案:

没有答案