我已将文件上传到服务器,但如何让图像在 jsp 页面中显示...我需要遵循哪些步骤?我想我需要服务器位置的路径...但是我如何获取路径或是否有更好的方法?
Controller .java
@RequestMapping(value="/addWebAchievement",method=RequestMethod.POST)
public ModelAndView addAchievement(@RequestParam("image") MultipartFile image,@RequestParam("title")String title,@RequestParam("note")String note,
Map<String,Object>m,@ModelAttribute("classObject") Clazz c ){
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
CustomUser user=null;
if (principal instanceof CustomUser) {
user = ((CustomUser)principal);
}
String username=user.getUsername();
ModelAndView model = new ModelAndView();
String imageName1=image.getOriginalFilename();
if (!image.isEmpty()) {
try {
byte[] bytes = image.getBytes();
// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "imageFiles");
System.out.println(dir);
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + imageName1);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
}catch(Exception e){}
}
addAchievement.jsp
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#userPhoto')
.attr('src', "<c:url value="e.target.result"/>")
.width(435)
.height(219);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
<img class="activator" src="<c:url value="/resources/image/user-bg.jpg" />" id="userPhoto" alt="user bg" id="default_image">
最佳答案
上传图片时预览图片,可以通过java脚本实现
<img src="images/<%=imageName%>" width="300px" height="150px" name="blogimage" id="imgprvw"/><input type="file" id="exampleInputFile" name="blogimage" onchange="showimagepreview(this)">
Java 脚本:
<script type="text/javascript">
function showimagepreview(input) {
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function(e) {
$('#imgprvw').attr('src', e.target.result);
}
filerdr.readAsDataURL(input.files[0]);
}
}
</script>
要显示已上传的图像,无需传递任何服务器位置,您可以直接使用类似的路径
<img src="images/<%=imageName%>" width="300px" height="150px" />
这里我假设根文件夹是图像。您可以使用用户文件夹名称
关于java - Spring MVC :- How do i get the uploaded image to display on jsp page as soon as the user selects the image. 我在这里使用Spring框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39193067/