`

Spring文件上传下载and图片上传及前台显示

阅读更多

之前感觉图片上传下载不就是通过流的形式么,最近做起来还真是棘手啊,所以说有的是就得先做后想才对。

  大体思路:把把图片存到文件夹中,然后把图片的名字存入数据库中。因公司用的Spring框架,所以只用Spring框架完成了上传,之后改变了方法完成的上传及前台显示,还是把网上找的Spring的上传下载贴出来,估计以后用得上,下载没有亲测~~

  Spring上传:

  springmvc.xml必须配置:1.

 

<bean id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8"/>

 

2.WEB-INF/lib下必加入:commons-fileupload.jarcommons-io-1.4.jar二个包

3.提交的form表单中属性加:enctype="multipart/form-data"

  单文件上传(以下为三种方法,第二种亲测):

@Controller
public class FileUploadController {


    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, BindException errors)
            throws Exception {


        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
                .getFile("file");


        String name = multipartRequest.getParameter("name");
        System.out.println("name: " + name);
        // 获得文件名:
        String realFileName = file.getOriginalFilename();
        System.out.println("获得文件名:" + realFileName);
        // 获取路径
        String ctxPath = request.getSession().getServletContext().getRealPath(
                "/")
                + "images/";
        // 创建文件
        File dirPath = new File(ctxPath);
        if (!dirPath.exists()) {
            dirPath.mkdir();
        }
        File uploadFile = new File(ctxPath + realFileName);
        FileCopyUtils.copy(file.getBytes(), uploadFile);
        request.setAttribute("files", loadFiles(request));
        return new ModelAndView("success");
    }


    @RequestMapping(value = "/upload2", method = RequestMethod.POST)
    public ModelAndView onSubmit2(HttpServletRequest request,
            HttpServletResponse response, BindException errors)
            throws Exception {


        // 转型为MultipartHttpRequest
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 根据前台的name名称得到上传的文件
        MultipartFile file = multipartRequest.getFile("file");
        // 获得文件名:
        String realFileName = file.getOriginalFilename();
        // 获取路径
        String ctxPath = request.getSession().getServletContext().getRealPath(
                "/")
                + "\\" + "images\\";
        // 创建文件
        File dirPath = new File(ctxPath);
        if (!dirPath.exists()) {
            dirPath.mkdir();
        }
        File uploadFile = new File(ctxPath + realFileName);
        FileCopyUtils.copy(file.getBytes(), uploadFile);
        request.setAttribute("files", loadFiles(request));
        return new ModelAndView("success");
    }


    @RequestMapping(value = "/upload3", method = RequestMethod.POST)
    public String upload(@RequestParam("file")
    MultipartFile image, HttpServletRequest request) throws IOException {


        String ctxPath = request.getSession().getServletContext().getRealPath(
                "/")
                + "\\" + "images\\";
        System.out.println("路径:" + ctxPath);
        File file = new File(ctxPath + "/" + image.getOriginalFilename());
        // FileCopyUtils.copy(image.getBytes(),new
        // File(ctxPath+"/"+image.getOriginalFilename()));
        try {
            image.transferTo(file); // 保存上传的文件
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        request.setAttribute("files", loadFiles(request));
        return "success";
    }


多文件上传(没有亲自测试,不过同时参考以下代码写的):

 

// 多文件上传
    @RequestMapping(value = "/upload4", method = RequestMethod.POST)
    public ModelAndView fileUpload(HttpServletRequest request,
            HttpServletResponse response, BindException errors)
            throws Exception {

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        String ctxPath = request.getSession().getServletContext().getRealPath(
                "/")
                + "\\" + "images\\";

        File file = new File(ctxPath);
        if (!file.exists()) {
            file.mkdir();
        }
        String fileName = null;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 上传文件名
            // System.out.println("key: " + entity.getKey());
            MultipartFile mf = entity.getValue();
            fileName = mf.getOriginalFilename();
            File uploadFile = new File(ctxPath + fileName);
            FileCopyUtils.copy(mf.getBytes(), uploadFile);
        }
        request.setAttribute("files", loadFiles(request));
        return new ModelAndView("success");
    }

    // @ModelAttribute("files")//此属性用于初始类时调用,但上传文件后不能时时反应上传文件个数,不适合动态数据
    public List<String> loadFiles(HttpServletRequest request) {
        List<String> files = new ArrayList<String>();
        String ctxPath = request.getSession().getServletContext().getRealPath(
                "/")
                + "\\" + "images\\";
        File file = new File(ctxPath);
        if (file.exists()) {
            File[] fs = file.listFiles();
            String fname = null;
            for (File f : fs) {
                fname = f.getName();
                if (f.isFile()) {
                    files.add(fname);
                }
            }
        }
        return files;
    }


文件下载:

 

@RequestMapping("/download/{fileName}")
    public ModelAndView download(@PathVariable("fileName")
    String fileName, HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        java.io.BufferedInputStream bis = null;
        java.io.BufferedOutputStream bos = null;

        String ctxPath = request.getSession().getServletContext().getRealPath(
                "/")
                + "\\" + "images\\";
        String downLoadPath = ctxPath + fileName;
        System.out.println(downLoadPath);
        try {
            long fileLength = new File(downLoadPath).length();
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition", "attachment; filename="
                    + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            response.setHeader("Content-Length", String.valueOf(fileLength));
            bis = new BufferedInputStream(new FileInputStream(downLoadPath));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
        return null;
    }
}


spring.xml(必须配置)

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"    
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <!-- 
        自动搜索@Controller标注的类
        用于指明系统从哪个路径下寻找controller,然后提前初始化这些对象。
    -->
    <context:component-scan base-package="net.liuzd.web" />

    <!--  ③:对模型视图名称的解析,即在模型视图名称添加前后缀 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />

   
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8">
        <property name="maxUploadSize">
            <value>104857600</value>
        </property>
        <property name="maxInMemorySize">
            <value>4096</value>
        </property>
    </bean>
</beans>


success.jsp

 

<%@ taglib  prefix="c" uri="/WEB-INF/c.tld"%>
<h1>Upload Successful</h1>
    <c:forEach var="month" items="${files}">
        <li><a href="${pageContext.request.contextPath}/download/${month}.do">${month}</a></li>
    </c:forEach>
  <hr><br>
  <a href="${pageContext.request.contextPath}/index.jsp">返回</a>


web.xml(必须配置)

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/classes/log4j.properties</param-value>
    </context-param>

    <context-param>
        <param-name>log4jRefreshInterval</param-name>
        <param-value>60000</param-value>
    </context-param>
    <context-param>
        <param-name>log4jExposeWebAppRoot</param-name>
        <param-value>false</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.springframework.web.util.Log4jConfigListener
        </listener-class>
    </listener>

    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>
            org.springframework.web.filter.CharacterEncodingFilter
        </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>false</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>*.do</url-pattern>
    </filter-mapping>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>*.jsp</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>


以上有些没有亲自测试,以下为自己写的图片上传及前台显示

 

/**上传图片
     * @param request  内置对象
     * @param response  内置对象
     * @param user  用户类
     * @param throws Exception  抛出异常
     * @return  
     * 
     */
    public void upload(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "file1", required = false) MultipartFile file , @ModelAttribute("book") com.tayh.projectCenter.vo.Book book){
        //获取上传文件
        if("".equals(file)||null==file){
            //上传图片为空或null,不进行操作            
        }else{
            //上传图片处理
            String file_path=request.getRealPath("/")+"upload";
            String file_real_file = "upload" + File.separator + "book" + File.separator;
            StringBuffer listFiles = new StringBuffer();
            StringBuffer listFileNames = new StringBuffer();
                if(!file.isEmpty()){
                    String fileName = file.getOriginalFilename();
                    System.out.println(fileName);
                    File files = new File(file_path, fileName);
                    if(!files.exists()){
                        files.mkdirs();
                    }
                    if(!fileName.equals(null) && !"".equals(fileName)){
                        try {
                            file.transferTo(files);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                        listFiles.append(file_real_file + fileName + ",");
                    listFileNames.append(fileName);
            }
            String f=listFileNames.toString();
            book.setBookPic(f);  
        }
   }
    
    /**将图片读到页面上
     * @param request  内置对象
     * @param response  内置对象
     * @param throws Exception  抛出异常
     * @return  
     * 
     */
    public void dumpImage(HttpServletRequest request, HttpServletResponse response){ 
        String paramPath = request.getParameter("path"); 
        String path ="";
        if(paramPath == null){ 
        path = (String) request.getAttribute("path"); 
        }else{ 
        try {
            path = new String(paramPath.getBytes("ISO8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        } 
        String picPath = request.getRealPath("/")+"upload"+ File.separator+path;
        InputStream in = null; 
        BufferedInputStream bis = null; 
        OutputStream out = null; 
        BufferedOutputStream bos = null; 

        // 判断文件是否存在 
        File file = new File(picPath); 
        if (!file.exists() || file.isDirectory()){ 
        return; 
        } 
        try { 
        in = new FileInputStream(picPath); 
        bis = new BufferedInputStream(in); 

        byte[] data = new byte[1024]; 
        int bytes = 0; 
        out = response.getOutputStream(); 
        bos = new BufferedOutputStream(out); 
        while ((bytes = bis.read(data, 0, data.length)) != -1) { 
        bos.write(data, 0, bytes); 
        } 
        bos.flush(); 
        } catch (Exception e) { 
        e.printStackTrace(); 
        } finally { 
        try { 
        if (bos != null) 
        bos.close(); 
        if (out != null) 
        out.close(); 
        if (bis != null) 
        bis.close(); 
        if (in != null) 
        in.close(); 
        } catch (IOException e) { 
        e.printStackTrace(); 
        } 
      } 
    }


前台页面bookAdd.jsp

 

<TR height="20px">
     <td align="center">图片上传</td>
     <td><input type="file" name="file1" id="file1" /></td>
</TR>


前台接收borrowBook.jsp

 

<td>
         <img id="bookImage" src="dumpImage.do?path=${list.bookPic }" style="height:120px;width:100px;" />
</td>

文章来源:点击打开链接

分享到:
评论

相关推荐

    Spring MVC 文件上传下载 后端 - Java.zip

    这个压缩包文件"Spring MVC 文件上传下载 后端 - Java.zip"包含的文档可能详细阐述了如何在Java后端实现这些功能。以下是关于Spring MVC中文件上传和下载的关键知识点: 1. **Spring MVC 框架**:Spring MVC是...

    Spring MVC文件上传下载

    在Spring MVC中,文件的上传和下载是常见的功能需求,这涉及到客户端与服务器之间的数据传输。本篇文章将深入探讨Spring MVC如何实现文件上传和下载。 ### 文件上传 1. **依赖配置**:在Spring MVC项目中,为了...

    基于idea spring boot图片的上传和下载

    在本文中,我们将深入探讨如何在IntelliJ IDEA(Idea)中利用Spring Boot实现图片的上传和下载功能,同时还会涉及如何判断图片的大小和格式类型。Spring Boot以其轻量级、便捷的特性,成为了现代Java开发中的首选...

    基于SpringBoot的文件上传系统,前后端分离,单文件上传,多文件上传,大文件上传,断点续传,文件秒传,图片上传

    基于SpringBoot的文件上传系统,前后端分离,单文件上传,多文件上传,大文件上传,断点续传,文件秒传,图片上传 项目经过严格测试,确保可以运行! 采用前后端分离的方式进行开发,实现了几种常用的文件上传功能...

    spring mvc上传 下载ftp文件

    spring mvc上传 下载ftp文件

    spring 文件上传实例

    文件上传在现代Web应用中有着广泛的应用,如用户头像上传、文档共享、图片库等。 首先,让我们了解一下Spring中的文件上传工作原理。Spring通过`CommonsMultipartResolver`类来处理multipart/form-data类型的HTTP...

    springcloud处理文件上传

    本话题主要探讨如何在Spring Cloud环境中处理文件上传,特别是在结合Feign和Zuul这两个组件时的实现方法。Feign是Spring Cloud的一个声明式HTTP客户端,用于简化服务间的调用;而Zuul则是作为API网关,提供路由、...

    Spring文件上传和下载所需的jar包.rar

    在Spring框架中,文件上传和下载是常见的功能需求,尤其在构建Web应用程序时。为了实现这一功能,开发者通常会依赖一些外部库,如Apache Commons IO和Apache Commons FileUpload。这两个库提供了强大的文件处理能力...

    Java Spring Boot应用程序中实现文件上传和下载功能

    ### Java Spring Boot应用程序中实现文件上传和下载功能 在现代Web开发中,文件上传与下载是常见的需求之一。Spring Boot框架提供了简洁的方式帮助开发者轻松实现这些功能。本文将详细介绍如何在Spring Boot项目中...

    struts+spring上传图片实例

    3. **Spring的参与**:Spring可以通过Service层处理业务逻辑,例如将上传的图片保存到数据库或者特定的文件系统中。同时,Spring的IoC(Inversion of Control)容器可以管理Action类和其他服务类的生命周期。 4. **...

    Spring 文件上传

    在Spring框架中,文件上传是常见的功能之...总结,Spring文件上传功能强大且灵活,但同时也需要谨慎处理,确保上传过程的安全性和稳定性。理解并熟练运用上述知识点,可以帮助你在实际开发中更好地处理文件上传的需求。

    Spring文件的上传和下载

    在Spring框架中,文件的上传和下载是常见的功能需求,特别是在构建Web应用程序时。下面将详细阐述如何在Spring中实现这一功能,以及涉及到的关键技术点。 1. **Servlet的注入和使用** 在Spring MVC中,我们通常...

    spring boot实现上传图片并在页面上显示

    在Spring Boot应用中,实现图片上传并显示是一个常见的需求,主要涉及到文件处理、服务器存储以及前端展示等技术。本文将详细讲解如何利用Spring Boot、Thymeleaf和Java来完成这个功能。 首先,我们需要理解Spring ...

    spring mvc上传文件

    在本文中,我们将深入探讨如何使用Spring MVC框架与Ajax技术结合来实现文件上传的功能。Spring MVC是Spring框架的一部分,提供了一种模型-视图-控制器(MVC)架构模式,用于构建Web应用程序。Ajax(Asynchronous ...

    spring mvc 上传文件显示进度

    在Spring MVC中实现文件上传并显示进度是一项常见的需求,特别是在用户需要等待较长时间的大型文件上传时。这个功能可以通过监听文件上传的进度并在前端实时更新来提升用户体验。下面将详细介绍如何利用Spring MVC...

    spring mvc ajax异步文件的上传和普通文件上传

    在Spring MVC框架中,文件上传是一项常见的功能,无论是普通的文件上传还是通过Ajax实现的异步文件上传,都为用户提供了更好的交互体验。本篇将详细讲解这两种方式的实现原理及步骤。 首先,让我们来理解一下普通...

    spring实现文件上传下载

    在Spring MVC框架中,文件上传和下载是常见的功能需求,尤其在Web应用中。Spring MVC提供了强大的支持来处理这些操作,使得开发者可以轻松地实现文件的上传和下载功能。下面将详细阐述如何利用Spring MVC来实现这两...

    Spring MVC实现文件的上传下载

    Spring MVC 是一个强大的Java Web开发框架,用于构建可维护、高性能和灵活的Web应用程序。它在Spring框架的基础上,为...开发者可以通过此副本学习和理解Spring MVC项目的组织方式,以及文件上传下载功能的实现细节。

    Spring MVC框架实现上传下载

    在Spring MVC框架中,实现文件上传和下载是常见的功能需求。以下将详细讲解如何使用Spring MVC来处理这两种操作,特别是图片的上传和多图片同时上传。 首先,为了启用Spring MVC对文件上传的支持,我们需要在配置...

Global site tag (gtag.js) - Google Analytics