我的简单网站是使用Spring。用户上传产品图片,网站将显示该图像(包括产品名称、价格等)。数据库只存储图像的详细信息,而我则将图像存储在目录中。问题是,我不知道图像商店应该在哪里。
// 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 (存储在数据库中)?
发布于 2014-08-18 04:16:21
为了向最终用户显示您的图像,您必须将其相对于您的web应用程序进行存储。
理想的方法将是在您的webapp中有一个专用文件夹,用于存储向上的内容,然后将相对的url发送给最终用户。
例如。
//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;https://stackoverflow.com/questions/25356188
复制相似问题