文章目录
 
 
- 前言
 
- 一、准备工作和实现步骤
 
- 二、代码编写
 
- 1.导入依赖
 
- 2.编写springmvc.xml配置
 
- 3.搭建JSP页面
 
- 4.编写控制层
 
- 5.编写一个上传成功的页面,并实现下载功能
 
- 6.测试
 
 
- 总结
 
  
 
前言
 
图片上传是一个在实际开发中经常遇到的业务场景,本次就来学习一下图片上传。
 
一、准备工作和实现步骤
 
- 使用IDEA新建一个maven项目
 
- 并导入相关依赖
 
- 完善项目结构
 
- 搭建前端页面
 
- 配置静态资源处理
 
- 编写后端controller
 
- 测试
 
二、代码编写
 
1.导入依赖
 
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.lzl</groupId>
  <artifactId>UploadDemo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>UploadDemo Maven Webapp</name>
  
  <url>http://www.example.com</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.12</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.3</version>
    </dependency>
    
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>
    
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
  </dependencies>
  <build>
    
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>*.xml</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
      </resource>
    </resources>
  </build>
</project>
 
2.编写springmvc.xml配置
 
<beans 	xmlns="http://www.springframework.org/schema/beans"
          xmlns:context="http://www.springframework.org/schema/context"
          xmlns:mvc="http://www.springframework.org/schema/mvc"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.springframework.org/schema/beans
							http://www.springframework.org/schema/beans/spring-beans.xsd
							http://www.springframework.org/schema/context
							http://www.springframework.org/schema/context/spring-context.xsd
							http://www.springframework.org/schema/mvc
							http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
    <context:component-scan base-package="com.lzl.controller"></context:component-scan>
    
    <mvc:annotation-driven></mvc:annotation-driven>
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
        <property name="prefix" value="/"></property>
        
        <property name="suffix" value=".jsp"></property>
    </bean>
    
    <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        
        <property name="defaultEncoding" value="utf-8"/>
        
        <property name="maxUploadSize" value="10485760"/>
    </bean>
    
    <mvc:default-servlet-handler/>
</beans>
 
3.搭建JSP页面
 
我们需要一个上传图片的按钮和文件域
 代码如下(示例):
 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>图片上传</title>
</head>
<body>
这是图片上传界面
<form action="/upload" enctype="multipart/form-data" method="post">
    请选择要上传的文件:<input type="file" name="upload"/><br />
    <input type="submit" value="上传">
</form>
</body>
</html>
 
 
 需要注意的是,form表单的enctype属性必须设置为multipart/form-data,提交方式必须选择post
 
 
4.编写控制层
 
我们需要接收jsp表单传输过来的文件类型对象,所以后端接收参数需要使用MultipartFile 这个类
 
@Controller
public class UploadController {
    @RequestMapping("/upload")
    public String upload(MultipartFile upload, HttpServletRequest request) throws IOException {
        System.out.println(upload);
        String filename = upload.getOriginalFilename();
        String realPath =  request.getServletContext().getRealPath("/");
        File uploadDir = new File(realPath,"upload");
        if(!uploadDir.exists()){
            uploadDir.mkdirs();
        }
        
        upload.transferTo(new File(uploadDir,filename));
        request.setAttribute("result","上传成功");
        
        String[] list = uploadDir.list();
        List<String> fileNames = Arrays.asList(list);
        request.setAttribute("fileNames",fileNames);
        return "result";
    }
   
}
 
5.编写一个上传成功的页面,并实现下载功能
 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@page isELIgnored="false" %>
<html>
<head>
  <title>成功页面</title>
</head>
<body>
${result} <br>
<%=request.getAttribute("result") %>
<c:forEach var="file" items="${fileNames}">
  <img src="${pageContext.request.contextPath}/upload/${file}"/>
  ${file} <a href="${pageContext.request.contextPath}/download?filename=${file}">下载</a>
</c:forEach>
</body>
</html>
 
后端的controller
 
@RequestMapping("/download")
    public void download(String filename, HttpServletResponse response, HttpServletRequest request) throws IOException {
        
        response.setHeader("content-disposition","attachment;filename="+filename);
        System.out.println(filename);
        ServletOutputStream outputStream = response.getOutputStream();
        String path = request.getServletContext().getRealPath("/upload");
        File file = new File(path, filename);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        outputStream.write(bytes);
        outputStream.close();
    }
 
6.测试
 
略
 
总结
 
本次图片上传只是一个最为原始的实现思路,实际开发中会有比这更好的实现思路