简体   繁体   English

无法使用Spring MVC在JSP中显示上传的图像(保存在文件系统中以及数据库中的存储位置,例如C:\\ Database \\ ..)

[英]Unable to display uploaded image (saved in file system and stored location on database eg., C:\Database\.. ) in jsp using spring mvc

I am developing a spring web MVC application. 我正在开发Spring Web MVC应用程序。 I have uploaded the images using Multipart and saved to file system(C:\\Database\\1.jpg). 我已经使用Multipart上传了图像并将其保存到文件系统(C:\\ Database \\ 1.jpg)。 I am saving the file location to the database. 我正在将文件位置保存到数据库。 Now, I need to display the images but donno what the reason is!! 现在,我需要显示图像,但是请不要显示原因!! I am unable to display images. 我无法显示图像。

Web.xml Web.xml

 <web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                             http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
    <display-name>Spring3 MVC Application</display-name>
    <servlet>
        <servlet-name>spring-web</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring-web</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

spring-web-servlet.xml spring-web-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<!-- Enables the Spring MVC @Controller programming model -->
<mvc:annotation-driven/>

<context:annotation-config/>
<context:component-scan base-package="com.springmaven"/>

<mvc:default-servlet-handler/>
<mvc:resources mapping="/**" location="/"/>
<mvc:resources mapping="C:/**" location="/" />

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
</bean>

<bean id="vendorDAO" class="com.springmaven.dao.VendorDAOImpl"/>
<bean id="sendEmail" class="com.springmaven.model.Email"/>
<bean id="hairStyleDAO" class="com.springmaven.dao.HairStyleDAOImpl"/>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/seturstyle?useSSL=false"/>
    <property name="username" value="root"/>
    <property name="password" value="root"/>
</bean>
<!--For FileUpload-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="uploadTempDir" ref="uploadDirResource" />
</bean>
<bean id="uploadDirResource" class="org.springframework.core.io.FileSystemResource">
    <constructor-arg>
        <value>C:/Database/</value>
    </constructor-arg>
</bean>
<!--For Sending Mail-->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.gmail.com"/>
    <property name="port" value="587"/>
    <property name="username" value="setuastyle@gmail.com"/>
    <property name="password" value="msitmsit"/>

    <!-- The name of the property, following JavaBean naming conventions -->
    <property name="javaMailProperties">
        <props>
            <prop key="mail.transport.protocol">smtp</prop>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
            <prop key="mail.debug">true</prop>
        </props>
    </property>
</bean>

HairStyleController HairStyleController

package com.springmaven.controllers;
import com.springmaven.dao.HairStyleDAOImpl;
import com.springmaven.model.HairStyle;
import com.springmaven.model.Vendor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

@Controller
public class HairStyleController {
@Autowired
HairStyleDAOImpl hairStyleDAO;

@RequestMapping(value = "/AddHairstyle")
public ModelAndView addHairstyleView() {
    ModelAndView modelView = new ModelAndView("vendor_AddHairStyle");
    return modelView;
}

@RequestMapping(value = "/EditHairstyleDetails")
public ModelAndView editHairstyleView() {
    ModelAndView modelView = new ModelAndView("vendor_editHairstyle");
    return modelView;
}

@RequestMapping(value = "/ViewHairstyles")
public ModelAndView viewAllHairstyleView(HttpSession session) {
    Vendor v = (Vendor) session.getAttribute("vendor");
    List<HairStyle> hairstyles=hairStyleDAO.getAllVendorhairstyles(v.getEmail());
    ModelAndView modelView = new ModelAndView("vendor_viewAllHairstyles");
    modelView.addObject("hairstyles",hairstyles);
    return modelView;
}

@RequestMapping(value = "/addHairstyleForm", method = RequestMethod.POST)
public ModelAndView addhairStyleForm(@ModelAttribute("hairstyle") HairStyle hairStyle, @RequestParam("files") MultipartFile[] files,
                             HttpServletRequest request) {
    ModelAndView modelView = new ModelAndView("redirect:/AddHairstyle");


    File pics[]=new File[files.length];

    for (int i = 0; i < files.length; i++) {
        MultipartFile file = files[i];
        try {
            byte barr[] = file.getBytes();
            String orgfileName = file.getOriginalFilename();
            int lastIndex = orgfileName.lastIndexOf('.');
            String extension = orgfileName.substring(lastIndex, orgfileName.length());

            String saloonName = hairStyle.getSaloonName();
            saloonName = saloonName.replace(" ", "");

            String path = request.getContextPath();
            File d = new File("C:\Database\");
            if(!d.exists())
                d.mkdir();

            File di = new File(d+ "\" + saloonName);
            if (!di.exists()) {
                boolean br = di.mkdir();
            }

            String hairStyleName = hairStyle.getHairstyleName();
            hairStyleName = hairStyleName.replace(" ", "");

            File dir = new File(di + "\" + hairStyleName);
            if (!dir.exists()) {
                boolean br = dir.mkdir();
            }
            // Create the file on server
            File serverFile = new File(dir+ "\" + hairStyleName + "_" + (i+1) + extension);

            BufferedOutputStream bout = new BufferedOutputStream(
                    new FileOutputStream(serverFile));

            bout.write(barr);
            bout.flush();
            bout.close();
            pics[i] = serverFile;
        } catch (Exception e) {
            System.out.println(e);
        }
    }
    hairStyle.setHairstylePics(pics);
    int i = hairStyleDAO.addHairStyle(hairStyle);
    if (i == 1) {
        modelView.setViewName("success");
    }
    else
    {
        modelView.addObject("error","Error occured during registration please do try again");
    }
    return modelView;
}
}

Now in view all hairstyles JSP, I am unable to load images. 现在,在所有发型JSP中,我无法加载图像。 showing empty blank white space. 显示空的空白空间。

Can anyone please solve this problem? 谁能解决这个问题?

Thanks in advance 提前致谢

Suppose you are storing images in FileSystem, You need to read the file path and get the image. 假设您将图像存储在FileSystem中,则需要读取文件路径并获取图像。

Here is the backend code(note that I used Spring framework) 这是后端代码(请注意,我使用了Spring框架)

 @RequestMapping(value = "/showImage/{saloonName}/{folder}/{hairstyleName}/{imageName}", method = RequestMethod.GET)
@ResponseBody
public void getImage(@PathVariable(value = "saloonName") String saloonName,
                     @PathVariable(value = "folder") String folder,
                     @PathVariable(value = "hairstyleName") String haistyleName,
                     @PathVariable(value = "imageName") String imageName, HttpServletResponse response) throws IOException {

    response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
    try {
        InputStream is = new FileInputStream("C:\\Database" + File.separator + saloonName +
                File.separator + folder + File.separator + haistyleName + File.separator + imageName + ".jpg");
        IOUtils.copy(is, response.getOutputStream());
    } catch (IOException e) {
        System.out.println("Couldn't open image from " + "C:\\Database\\" + saloonName + "\\" + folder + "\\" + haistyleName + "\\" + imageName + ".jpg");
    }
}

Whereas, In the front end 而在前端

<img class="group list-group-image" src="/showImage/${hairstyles.get(i).hairstylePics[0]}"/>

Here In the above code, I have used Servlet for request/response model. 在上面的代码中,我已将Servlet用于请求/响应模型。 /showImage/{folder_path}/image_name when I request an image as specified above It will request mapping function to load the image from the filesystem and send the response as image/jpeg, image/jpg, image/png, image/gif format. / showImage / {folder_path} / image_name当我如上所述请求图像时,它将请求映射功能从文件系统加载图像并以image / jpeg,image / jpg,image / png,image / gif格式发送响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM