首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javaweb中图像的上传与显示

Javaweb中图像的上传与显示
EN

Stack Overflow用户
提问于 2014-08-18 04:01:56
回答 1查看 1.5K关注 0票数 0

我的简单网站是使用Spring。用户上传产品图片,网站将显示该图像(包括产品名称、价格等)。数据库只存储图像的详细信息,而我则将图像存储在目录中。问题是,我不知道图像商店应该在哪里。

代码语言:javascript
复制
// Creating the directory to store file
            File dir = new File(imageDirectory);
            if (!dir.exists())
                dir.mkdirs();

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath()
                    + File.separator + name);

例如,当变量imageDirectory的值为"\temp“时,我的应用程序将将图像存储在"D:\temp”中,并且我不知道如何将图像url显示在我的网站上

当变量imageDirectory的值为"temp“时,我的应用程序将图像存储在”D:\soft\sts-bundle\3.5.1“中,我不知道如何在我的网站上显示图像url。

那么,我应该在哪里存储上传图像,以及如何获得上传的图像url (存储在数据库中)?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-18 04:16:21

为了向最终用户显示您的图像,您必须将其相对于您的web应用程序进行存储。

理想的方法将是在您的webapp中有一个专用文件夹,用于存储向上的内容,然后将相对的url发送给最终用户。

例如。

代码语言:javascript
复制
  //request is an instance of HttpServletRequest

  File uploadDirectory = new File(request.getSession().getServletContext().getRealPath("/uploads"));

  if (!uploadDirectory.exists()) {
      uploadDirectory.mkdirs();
  }

  File reportFile = new File(reportDirectory.getAbsolutePath(), fileName);

  String requestUrl = request.getRequestURL().toString();
  requestUrl = requestUrl.substring(0, requestUrl.lastIndexOf("/") + 1) + "uploads/" + fileName;
  return requestUrl;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25356188

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档