mardi 24 mai 2016

How to convert absolute path to a relative path so that it can be referenced from an img tag? java web

Creating a web application that lets users upload images. The code works but having trouble understanding how to get the images in a relative path so that it can be referenced from an img src="" tag?

So far the code takes the multipart request and stores the file in an absolute path on server but this cannot be referenced from an < img > tag..

Any ideas on how to go about this?

UploadFile.java (servlet)

package userServlets;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50) // 50MB
@WebServlet("/UploadFile")
public class UploadFile extends HttpServlet {

    private boolean isMultipart;

    private static final long serialVersionUID = 1L;

    public UploadFile() {
        super();

    }

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

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

        // get session
        HttpSession session = request.getSession();

        // get the save location for files that user uploads to web app
        String appPath = request.getServletContext().getRealPath("/uploads");

        // get the name of the currently logged in user
        String user = session.getAttribute("loggedInUser").toString();

        // create the user's own folder in uploads folder of server.
        String directory = appPath + File.separator + user;
        File fileSaveDir = new File(directory);
        if (!fileSaveDir.exists()) {
            fileSaveDir.mkdir();
        }

        // get the path of the users folder location as a file
        File uploads = new File(
                request.getSession().getServletContext().getRealPath("/uploads" + File.separator + user));

        // Check if request is multipart, if not, sends user back to uplaod page
        // (test.jsp)
        isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
            RequestDispatcher rd = request.getRequestDispatcher("test.jsp");
            rd.forward(request, response);
        }

        // Suspicious looking stuff not too sure of but works i guess :/
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(uploads);
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

        ServletFileUpload upload = new ServletFileUpload(factory);

        try {

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

            if (formItems != null && formItems.size() > 0) {
                // iterates over form's fields
                for (FileItem item : formItems) {
                    // processes only fields that are not form fields
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        long sizeInBytes = item.getSize();
                        String filePath = uploads + File.separator + fileName;
                        File storeFile = new File(filePath);

                        // saves the file on disk
                        item.write(storeFile);
                        request.setAttribute("message", "Upload has been done successfully!");

                        request.setAttribute("filename", fileName);

                        // *STORE THIS IN DATABASE
                        request.setAttribute("filepath", filePath);

                        request.setAttribute("filesize", sizeInBytes);

                    }

                }
            }
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {

            request.setAttribute("directory", directory);

            RequestDispatcher rd = request.getRequestDispatcher("test.jsp");

            rd.forward(request, response);

        }

    }

}

test.jsp (upload form)

  <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://ift.tt/kTyqzh">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
      <title>Insert title here</title>
</head>
<body>
    <div class="jumbotron">

        <div class="container">

            <form method="post" enctype="multipart/form-data" action="UploadFile">


                <input type="text" name="description" /> <input type="file"
                    name="file" /> <input type="submit" />


            </form>


        </div>


    </div>
    <h1>"${directory}"</h1>
    <h1>"${message}"</h1>
    <h1>"${filepath}"</h1>
    <h1>"${filename}"</h1>
    <h1>"${filetype}"</h1>
    <h1>"${filesize}"</h1>

    <img src="${filepath}">


    <hr />
    <div class="jumbotron">

        <img alt="" src="hmmmmmm">

    </div>




</body>
</html>




Aucun commentaire:

Enregistrer un commentaire