SSM框架+MySql数据库实现图片的上传、回显、展示、下载

前言

最近很多人反映,当spring+springmvc+mybatis整合之后,不知道图片的上传、回显、展示、下载如何实现。其实ssm框架已经帮我们封装好了这块,我们要做的就是进行相关的配置和调用。今天我就配置这块进行一个简单讲解。

SSM框架整合可参考:https://blog.csdn.net/guigu2012/article/details/72926481

1、导入jar包

如果是maven工程,只需要在pom.xml添加如下代码:

        <!-- 上传下载需要设计到的jar包 -->
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
 
        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>

2、编写工具类

package com.yueqian.ssm.common;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 图片工具类
 * @author gzlx
 *
 */
public class ImageUtils {
	/**
	 * 上传图片
	 * @param request
	 * @param book
	 * @param pictureFile
	 * @throws IOException
	 */
	public static String upload(HttpServletRequest request,
			MultipartFile pictureFile) throws IOException {
		String imgPath = null;//装配后的图片地址
		//上传图片
		if(pictureFile!=null&&!pictureFile.isEmpty()){
			// 使用UUID给图片重命名,并去掉四个“-”
			String name = UUID.randomUUID().toString().replaceAll("-", "");
			// 获取文件的扩展名
			String ext = FilenameUtils.getExtension(pictureFile
					.getOriginalFilename());
			// 设置图片上传路径
			String url = request.getSession().getServletContext()
					.getRealPath("/upload");
			// 检验文件夹是否存在
			isFolderExists(url);
			// 以绝对路径保存重名命后的图片
			pictureFile.transferTo(new File(url + "/" + name + "." + ext));
			// 装配图片地址
			imgPath = "upload/" + name + "." + ext;
		}
		return imgPath;
	}
	/**
	 * 验证文件夹是否存在
	 * @param strFolder
	 * @return
	 */
	public static boolean isFolderExists(String strFolder){
           File file = new File(strFolder);
        
           if (!file.exists())
           {
              if (file.mkdir())
              {
                  return true;
              }
              else{
                  return false;
              }
               
           }
           System.out.println("-----------------文件上传路径:"+strFolder);
           return true;
       }
	/**
	 * 获取目录下所有文件(按时间排序)
	 * @param path
	 * @return
	 */
	public static List<File> getFileSort(String path) {
	    List<File> list = getFiles(path, new ArrayList<File>());
	    if (list != null && list.size() > 0) {
	        Collections.sort(list, new Comparator<File>() {
	            public int compare(File file, File newFile) {
	                if (file.lastModified() < newFile.lastModified()) {//降序<;升序>
	                    return 1;
	                } else if (file.lastModified() == newFile.lastModified()) {
	                    return 0;
	                } else {
	                    return -1;
	                }
	            }
	        });
	    }
	    return list;
	}
	/**
	 *  获取目录下所有文件
	 * @param realpath
	 * @param files
	 * @return
	 */
	public static List<File> getFiles(String realpath, List<File> files) {
	    File realFile = new File(realpath);
	    if (realFile.isDirectory()) {
	        File[] subfiles = realFile.listFiles();
	        for (File file : subfiles) {
	            if (file.isDirectory()) {
	                getFiles(file.getAbsolutePath(), files);
	            } else {
	                files.add(file);
	            }
	        }
	    }
	    return files;
	}

}

3、文件上传

3.1 修改spirngmvc.xml文件

 

  
	<!-- 定义文件上传解析器 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 设定默认编码 -->
		<property name="defaultEncoding" value="UTF-8"></property>
		<!-- 设定文件上传的最大值5MB,5*1024*1024 -->
		<property name="maxUploadSize" value="5242880"></property>
        <!-- 其他的大家可以自行配置,不影响主功能-->
	</bean>

3.2 修改jsp界面

上传图片的<input>标签中,name属性的名字和实体bean的属性名称不能一致,同时form表单加enctype属性:

注意:form表单中可以同时放置普通的表单数据

<form method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/addUser.do" >
<input type="file" name="pictureFile" id="pictureFile" value="请选择图片" />

3.3 在Controller中编写相关的代码

 

/**
	 * 添加用户信息
	 * @param user,封装表单中除图片地址以外的其他数据(要求<input>中的name跟实体类中的属性一致)
	 * @param request,用来获取文件的存储位置等
	 * @param pictureFile,封装上传图片的信息如大小、文件名、扩展名等,(要求<input>中的name跟次命名一致)。
	 * @return
	 * 注意:图片提交input输入框的name属性值要与Controller中MultipartFile
	 * 接口所声明的形参名一致,不然需要用@RequestParam注解绑定
	 */
	@RequestMapping(path = "/addUser.do", method = RequestMethod.POST)
	public String addUser(User user, HttpServletRequest request, MultipartFile pictureFile) {
		// 得到上传图片的地址
		String imgPath;
		try {
            //ImageUtils为之前添加的工具类
			imgPath = ImageUtils.upload(request, pictureFile);
			if (imgPath != null) {
				// 将上传图片的地址封装到实体类
				user.setPic(imgPath);
				System.out.println("-----------------图片上传成功!");
			}else{
                System.out.println("-----------------图片上传失败!");
            }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("----------------图片上传失败!");
		}
		//将数据提交到数据库(包含文件和普通表单数据)
		int rowNo = userService.saveUser(user);
		if (rowNo > 0) {
			System.out.println("----------------------用户添加成功!");
			// 转发:forword,重定向:redirect
			return "redirect:/user/findUsers.do";
		} else {
			System.out.println("----------------------用户添加失败!");
			return "addUser";
		}

	}

4、图片回显

在jsp界面显示图片的<img>标签中,通过el表达式来动态给src赋值

<!--${book.pic}数据库中存储的:upload/图片名称.图片后缀-->
<img src="${pageContext.request.contextPath}/${book.pic }"/>

以上内容为图片【其他文件等同】的上传以及图片的回显,

5、获取本地文件,并通过jsp进行展示

5.1 在Controller中编写相关代码

    /**
	 * 文件列表的显示
	 * @param request
	 * @param m:封装数据,这里主要是封装List<File>
	 * @return
	 */
	@RequestMapping(value = "/showFile.do")
	public String showFile(HttpServletRequest request, Model m) {
		ServletContext servletContext = request.getServletContext();
		//动态获取存放文件的本地路径【绝对路径】
		String path = servletContext.getRealPath("/upload");		
		//获取文件夹下的所有文件【ImageUtils为之前编写的工具类】
		//File[] fileList = new File(path).listFiles();//原生写法
		List<File> fileList = ImageUtils.getFileSort(path);
		m.addAttribute("fileList", fileList);
		return "showFile";
	}

5.2 通过jsp进行文件展示

showFile.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
	<h3 align="center">文件列表展示</h3>
	<c:choose>
		<c:when test="${not empty fileList }">
			<!--索引-->
			<c:set var="index" value='1'></c:set>
			<c:forEach items="${fileList }" var="file">
				<!-- filename:文件的名字,不带UUID -->
				<c:set var="filename"
					value='${fn:substring(file.name,fn:indexOf(file.name,"_")+1,fn:length(file.name)) }' ></c:set>
				<!-- filefullname:文件的名字,带UUID c:set中使用“\\”会报错,要使用“\\\\”,其他地方使用“\\”即可-->
				<c:set var="filefullname"
					value='${fn:split(file.path,"\\\\")[fn:length(fn:split(file.path,"\\\\"))-1] }'></c:set>
				<!-- rootdir:文件的目录 -->
				<c:set var="rootdir"
					value='${pageContext.request.contextPath}/upload/'></c:set>
				<div>
					<img alt='${filefullname}' src='${rootdir.concat(filefullname) }' style="width: 160px;height: 100px;border-radius: 5px;"/>
					<!-- 文件的全路径 -->
					<a href="${pageContext.request.contextPath}/user/fileDownload.do?fileName=${filefullname}">下载</a>
				</div>
				<!-- 每行显示5张图片 -->
				<c:if test="${index%5==0 }">
					<br>
				</c:if>
				<!--索引+1-->
				<c:set var="index" value='${index+1 }'></c:set> 
			</c:forEach>
		</c:when>
		<c:otherwise>
                     暂无数据
        </c:otherwise>
	</c:choose>

</body>
</html>

6、文件下载

在jsp中,通过<a ></a>标签绑定下载文件的路径,见上文5.2所示

6.1 在Controller中编写相关代码

       /**
	 * 文件下载
	 * 用ResponseEntity<byte[]> 返回值完成文件下载
	 * @param request
	 * @param fileName:文件的名称
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "fileDownload.do")
	public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, @RequestParam(value = "fileName") String fileName)
			throws Exception {
		String fName = fileName.substring(fileName.lastIndexOf("_") + 1); // 从uuid_name.jpg中截取文件名
		//根据文件的绝对路径,获取文件
		File file = new File(request.getServletContext().getRealPath("/upload/"+fName));
        //设置请求头
		HttpHeaders headers = new HttpHeaders();
		fileName = new String(fileName.getBytes("utf-8"), "iso8859-1");
		headers.add("Content-Disposition", "attachment;filename=" + fileName);
		HttpStatus statusCode = HttpStatus.OK;
		ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, statusCode);
		return response;
	}

到此,整个图片上传、回显、展示、下载就全部完成了,希望能够帮助到各位朋友!

 

  • 26
    点赞
  • 194
    收藏
    觉得还不错? 一键收藏
  • 19
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值