【问题标题】:How to get the absolute path in Java如何在Java中获取绝对路径
【发布时间】:2014-09-12 23:40:34
【问题描述】:

目前我正在从浏览器上传一张图片。现在在后端有 java 代码,我正在检索这些图片并转换为字节数组并存储到数据库中,这部分工作实际上很好

代码如下:

String fromLocal = "D:/123.jpg";
        File file = new File(fromLocal);
        InputStream inputStream = null;
        byte[] bFile= null;
        byte[] imageData = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
            bFile = new byte[8192];
            int count;
            while((count = inputStream.read(bFile))> 0){
                baos.write(bFile, 0, count);
            }
            bFile = baos.toByteArray();
            if(bFile.length > 0){
                imageData = bFile;
            }
            baos.flush();
            inputStream.close();
        } catch (Exception ioe) {
            //throw ioe;
        }

问题是每当我尝试硬编码图像路径(如这里的 D:/123.jpg)时,它都可以正常工作。现在它的用户依赖和客户端依赖他可以从任何驱动器和任何目录加载图像。我没有使用 servlet 的特权。 我的查询是:

1.现在,如果我尝试从浏览器上传来自 D:/123.jpg 的相同图像,我只会得到 123.jpg 而不是像 D:/123.jpg 这样的绝对路径。因为现在同样无法处理图像。

2.如何知道用户尝试上传图像的特定路径。(假设用户从 C:/images/123.jpg 上传图像),那么如何获取这个绝对路径。

我已尽力详细说明我的问题,如果有不清楚的地方请告诉我,我会尝试以其他方式解释。

【问题讨论】:

  • 你在寻找 Java 中的 getAbsolutePath() 方法吗
  • 用户在哪里上传文件?上传意味着您正在使用一个网站,但您说“我没有使用 servlet 的特权”。您的软件在哪里运行?
  • 关于问题 2,我很确定现在大多数浏览器出于安全原因不会发布文件的完整路径。
  • @George 他们从来没有这样做过。它始终只是文件名。文件在用户机器上的位置与网站没有任何关系。

标签: java image file fileinputstream absolute-path


【解决方案1】:

如果用户将文件上传到您的 servlet,则该文件包含在请求正文中,它不在服务器上的任何路径上。最终用户的 client 机器上的路径无关紧要(无论如何您都无法访问它,甚至客户端也无法访问)。

这里有关于文件上传的 Java EE 6 教程:http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html

基本上(从该示例中),如果用于上传的字段名称为 file,您可以在 servlet 中执行此操作:

final Part filePart = request.getPart("file");
InputStream filecontent = null;

然后在try/catch:

filecontent = filePart.getInputStream();

...并使用流中的数据。

这是上面教程的来源(以防以后有人阅读时无法访问)。在这种情况下,它会将文件写入文件服务器端,但在您的情况下,您当然会填充您的 imageData(我认为您将其放入数据库中)。

@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig
public class FileUploadServlet extends HttpServlet {

    private final static Logger LOGGER = 
            Logger.getLogger(FileUploadServlet.class.getCanonicalName());

    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        // Create path components to save the file
        final String path = request.getParameter("destination");
        final Part filePart = request.getPart("file");
        final String fileName = getFileName(filePart);

        OutputStream out = null;
        InputStream filecontent = null;
        final PrintWriter writer = response.getWriter();

        try {
            out = new FileOutputStream(new File(path + File.separator
                    + fileName));
            filecontent = filePart.getInputStream();

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

            while ((read = filecontent.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            writer.println("New file " + fileName + " created at " + path);
            LOGGER.log(Level.INFO, "File{0}being uploaded to {1}", 
                    new Object[]{fileName, path});
        } catch (FileNotFoundException fne) {
            writer.println("You either did not specify a file to upload or are "
                    + "trying to upload a file to a protected or nonexistent "
                    + "location.");
            writer.println("<br/> ERROR: " + fne.getMessage());

            LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}", 
                    new Object[]{fne.getMessage()});
        } finally {
            if (out != null) {
                out.close();
            }
            if (filecontent != null) {
                filecontent.close();
            }
            if (writer != null) {
                writer.close();
            }
        }
    }

    private String getFileName(final Part part) {
        final String partHeader = part.getHeader("content-disposition");
        LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(
                        content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }
}

【讨论】:

  • @Crowder--看来我的项目不会使用 servlets API 3.0 和 tomcat 7.0..任何其他解决方法
  • @UdayKonduru:有Apache Commons FileUpload。从根本上说:数据在请求中,所以你从请求中读取它。
【解决方案2】:

如果您使用浏览器提交表单,您无法获取绝对路径,因为protocol(HTTP)
图像文件将附加到请求对象(没有任何绝对路径)。就是这样!!!

【讨论】:

  • 我的猜测是,虽然它是正确的,但它并不能有效地回答这个问题。 @Jaykishan:不要指望反对者发表评论,SE管理层积极劝阻。 :-) (显然它只会导致争论或其他东西......)
  • @T.J.Crowder 非常正确,我只是把这个人带到了技术边界。
猜你喜欢
  • 2023-03-31
  • 2013-08-21
  • 2018-12-27
  • 1970-01-01
  • 2010-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-14
相关资源
最近更新 更多