SSM实现文件/图片上传与下载

SSM实现文件/图片上传与下载

添加依赖

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3</version>
</dependency>
<!-- 文件上传 -->
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>1.3.2</version>
  </dependency>

首先在spring-mvc.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>

实现上传的Controller
注意from表单的enctype应设置为"multipart/form-data"
指定传输数据为二进制类型,比如图片、mp3、文件。

 @RequestMapping("/addhouse")
    public String addHouse(HouseList houseList, HttpServletResponse response, MultipartFile file, ModelMap map)
           throws IOException {
       String uuid= UUID.randomUUID().toString();
       houseList.setId(uuid.replace("-",""));
       /**
                * 上传图片
                */
       //图片上传成功后,将图片的地址写到数据库
       String filePath = "E:\\upload";//保存图片的路径
       //获取原始图片的拓展名
       String originalFilename = file.getOriginalFilename();
       //新的文件名字
       String newFileName = UUID.randomUUID().toString().replace("-","")+originalFilename;
       //封装上传文件位置的全路径
       File targetFile = new File(filePath,newFileName);
       //把本地文件上传到封装上传文件位置的全路径
       file.transferTo(targetFile);
       houseList.setImage(newFileName);


       houseListSevice.insert(houseList);
       return "redirect:/houselist";
   }

图片展示

 @RequestMapping("/show")
    public String show(Model model,@RequestParam("id") String id){
    HouseList houseList=houseListSevice.show(id);
    if (houseList!=null){
        model.addAttribute("list",houseList);
        return "admin/show";
    }
    else {
        return "admin/error";
    }

    }

jsp页面代码`

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"/>

    <title>详情</title>
</head>
<body>
<table class="table table-bordered table-hover">
        <tr>
            <th><c:if test="${list.image !=null }">
                <img id="images" alt="" src="/image/${list.image }">//图片展示
            </c:if> </th>
            <th>    <a id="a" href="${pageContext.request.contextPath}/fileDownload.do?fileName=${list.image}" >
                </a>
            </th>
        </tr>
</table>
</body>
<script >
    var filename="${list.image}"
    var file=filename.slice(32)//截取字符串去掉UUID
    document.getElementById("a").innerText=file//设置到<a>标签
</script>
</html>

实现文件下载的Controller

@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("E:/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;
    }

<下载的链接在上面的jsp代码里 id=“a”>
特别注意的是需要将上传路径配置到tomcat中

1.修改idea的tomcat配置

选择本地上传的文件夹 更改路径为image
选择上传的文件夹  更改路径为image

2.修改server.xml

打开 Tomcat conf 文件夹下的 server.xml 文件,在 Host 节点下添加如下配置:

docBase 为文件保存路径, path 为文件访问路径。

SSM 框架中实现文件上传功能一般需要以下步骤: 1. 在前端页面中添加文件上传表单,例如: ```html <form action="文件上传处理的 URL" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="上传"> </form> ``` 2. 在后端代码中编写文件上传处理逻辑,一般包括以下步骤: - 创建一个 MultipartFile 对象,该对象包含上传的文件数据; - 获取文件名和文件类型等信息; - 指定文件上传保存的路径; - 将文件保存到指定路径。 以下是一个简单的文件上传处理的示例代码: ```java @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public String upload(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { // 文件为空,返回错误信息 return "上传文件不能为空"; } String fileName = file.getOriginalFilename(); // 获取文件名 String fileType = fileName.substring(fileName.lastIndexOf(".") + 1); // 获取文件类型 String filePath = "文件上传保存的路径"; // 指定文件保存的路径 try { // 将文件保存到指定路径 File dest = new File(filePath + fileName); file.transferTo(dest); // 返回上传成功信息 return "上传成功"; } catch (IOException e) { e.printStackTrace(); // 返回上传失败信息 return "上传失败"; } } ``` 对于图片上传处理,除了上述步骤外,还需要在前端页面中添加图片预览功能,例如: ```html <form action="文件上传处理的 URL" method="post" enctype="multipart/form-data"> <input type="file" name="file" onchange="previewImage(this)"> <img id="preview" src="" style="display:none"> <input type="submit" value="上传"> </form> <script> function previewImage(fileInput) { var preview = document.getElementById("preview"); var file = fileInput.files[0]; var reader = new FileReader(); reader.onload = function (e) { preview.src = e.target.result; preview.style.display = "block"; }; reader.readAsDataURL(file); } </script> ``` 这样上传图片时,用户就可以在选择图片后实时预览图片,提高用户体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值