Where/How 将 images/files 存储在 spring mvc 中
Where/How to store images/files in spring mvc
我正在 Spring MVC 和 Hibernate 的电子商务应用程序中工作,我需要在其中存储大量图像。
我想将图像保存在文件系统上(在服务器本身上以减少数据库的负载)。我的疑问是我应该在我的项目中保存图像的确切位置?
正如我浏览过一些博客,其中提到图像不应保存在 war
文件的文件夹中,因为它可能会在下一个版本的应用程序发布时导致问题(备份所有图像并再次手动放置它们)
请让我知道我到底需要在哪里保存图像以及如何在我们的 java class.
中获取该文件夹路径
您可以store/upload容器中的文件。使用 request.getRealPath("/")
访问路径。
示例:
byte[] bytes = fileInput.getBytes();
//bytes to string conversion
fileToStr = new String(bytes, "UTF-8");
System.out.println(fileToStr);
String name=fileInput.getOriginalFilename();
String ext=name.substring(name.lastIndexOf("."),name.length());
fileName=""+System.currentTimeMillis()+ext;
String rpath=request.getRealPath("/"); //path forstoring the file
System.out.println(rpath);
File file=new File(rpath,"csv");
if(!file.exists()){
file.mkdirs();
}
File temp=new File(file,fileName);
System.out.println("Path : "+temp);
FileOutputStream fos= new FileOutputStream(temp);
fos.write(bytes);
fos.close();
您可以创建一个控制器来 return 图像数据并用它显示在您的 jsp 上。
示例控制器:
@RequestMapping(value = "/getImage/{imageId}")
@ResponseBody
public byte[] getImage(@PathVariable long imageId, HttpServletRequest request) {
String rpath = request.getRealPath("/");
rpath = rpath + "/" + imageId; // whatever path you used for storing the file
Path path = Paths.get(rpath);
byte[] data = Files.readAllBytes(path);
return data;
}
并使用以下代码显示:
<img src="/yourAppName/getImage/560705990000.png" alt="myImage"/>
HTH!
我正在 Spring MVC 和 Hibernate 的电子商务应用程序中工作,我需要在其中存储大量图像。
我想将图像保存在文件系统上(在服务器本身上以减少数据库的负载)。我的疑问是我应该在我的项目中保存图像的确切位置?
正如我浏览过一些博客,其中提到图像不应保存在 war
文件的文件夹中,因为它可能会在下一个版本的应用程序发布时导致问题(备份所有图像并再次手动放置它们)
请让我知道我到底需要在哪里保存图像以及如何在我们的 java class.
您可以store/upload容器中的文件。使用 request.getRealPath("/")
访问路径。
示例:
byte[] bytes = fileInput.getBytes();
//bytes to string conversion
fileToStr = new String(bytes, "UTF-8");
System.out.println(fileToStr);
String name=fileInput.getOriginalFilename();
String ext=name.substring(name.lastIndexOf("."),name.length());
fileName=""+System.currentTimeMillis()+ext;
String rpath=request.getRealPath("/"); //path forstoring the file
System.out.println(rpath);
File file=new File(rpath,"csv");
if(!file.exists()){
file.mkdirs();
}
File temp=new File(file,fileName);
System.out.println("Path : "+temp);
FileOutputStream fos= new FileOutputStream(temp);
fos.write(bytes);
fos.close();
您可以创建一个控制器来 return 图像数据并用它显示在您的 jsp 上。
示例控制器:
@RequestMapping(value = "/getImage/{imageId}")
@ResponseBody
public byte[] getImage(@PathVariable long imageId, HttpServletRequest request) {
String rpath = request.getRealPath("/");
rpath = rpath + "/" + imageId; // whatever path you used for storing the file
Path path = Paths.get(rpath);
byte[] data = Files.readAllBytes(path);
return data;
}
并使用以下代码显示:
<img src="/yourAppName/getImage/560705990000.png" alt="myImage"/>
HTH!