繁体   English   中英

如何将绝对路径转换为相对路径,以便可以从img标记引用它? java web

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

创建允许用户上传图像Web应用程序 代码有效,但无法理解如何在相对路径中获取图像,以便可以从img src =“”标记引用它

到目前为止,代码接受多部分请求并将文件存储在服务器上的绝对路径中,但不能从<img>标记引用它。

关于如何解决这个问题的任何想法?

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(上传表格)

  <%@ 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://www.w3.org/TR/html4/loose.dtd">
<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>

阅读此链接后想出来

如果你完全控制images文件夹,那么只需将包含所有图像的文件夹,例如/ images直接放在servletcontainer的deploy文件夹中,例如/ webapps文件夹,如果是Tomcat,则/ / domains / domain1 / applications文件夹,如果是GlassFish 。 无需进一步配置。

将文件拖放到ide中的Web应用程序文件夹中。 在此输入图像描述

然后你这样做 在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM