代码基本是固定的,拿去用的话只要改一下文件路径即可
一、先看怎么使用
1、上传
访问http://localhost:8080/ 会打开index.html,显示了默认图片(自己设置)
D:\test中只有一张默认图片(之后上传的图片都会保存在这里)
点击 选择文件,这里我选择1.jpg
点击确认之后,前端的图片改变了(功能是在Index.html实现的)
点击 提交,提示我们 上传成功
在IDEA中可以看到输出了文件名称以及前端form传进来的数据
在文件夹可以看到图片进来了,而且名字改为了 2.jpg(在FileController实现)
2、下载
直接点击这个超链接会进行下载
右上角弹出下载的选项,就可以下载了
二、再看代码和解析
1、项目结构
2、pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.jiyu</groupId>
<artifactId>sp06-file</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sp06-file</name>
<description>sp06-file</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3、index.html
当我们选择照片时就会触发方法uploadAvatar(),将我们上传的照片回显在前端
<!DOCTYPE html>
<html lang="en">
<head>
<title>test for file</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript">
function uploadAvatar(){
//1 创建文件读取对象
var reader=new FileReader();
//文件存储在file表单元素的files属性中,它是一个数组
//没有返回值,但是读取完毕后,将读取结果存储在对象的result中
var fil=document.getElementById("file1").files;
reader.readAsDataURL(fil[0]);
//当读取成功后触发
reader.onload=function(){
document.getElementById("img1").src=reader.result;
};
}
</script>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
学号:<input type="text" name="sno"/><br/>
姓名:<input type="text" name="sname"/><br/>
照片:<img id="img1" src="/test/default.png" style="height:100px;width:100px;border-radius:50px"><br><!--src="/test/default.png"使用了虚拟路径,不然访问不到-->
<input id="file1" type="file" name="spicture" onchange="uploadAvatar()"/><br/>
<input type="submit" value="提交"/>
</form>
<br>
<a href="/download">下载1.jpg</a>
</body>
</html>
4、FileController.java
package com.jiyu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@Controller
public class FileController {
//文件上传
@RequestMapping(value = "upload")
@ResponseBody
public String upload(@RequestParam("spicture") MultipartFile file,String sno,String sname) {
if (file.isEmpty()) {
return "文件为空";
}
// 获取文件名
String fileName = file.getOriginalFilename();
//修改上传完成后的文件名(没有该需求可以删除这行)
fileName="2.jpg";
System.out.println(("上传的文件名为:" + fileName));
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
System.out.println(("上传的后缀名为:" + suffixName));
// 文件上传后的路径
String filePath = "D://test//";
// 解决中文问题,liunx下中文路径,图片显示问题
// fileName = UUID.randomUUID() + suffixName;
File dest = new File(filePath + fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
System.out.println("上传成功!\nsno: "+sno+"\nsname: "+sname);
return "上传成功";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
//文件下载
@RequestMapping("/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
String fileName = "1.jpg";
if (fileName != null) {
//当前是从该工程的static//File//下获取文件 然后下载
//获取根目录
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if(!path.exists()) path = new File("");
System.out.println("path:"+path.getAbsolutePath());
//如果上传目录为/static/File/,则可以如下获取:
File upload = new File(path.getAbsolutePath(),"static/File/");
if(!upload.exists()) upload.mkdirs();
// System.out.println("upload url:"+upload.getAbsolutePath());
String realPath=upload.getAbsolutePath();
// 也可以使用绝对路径,但是很明显不够灵活
// String realPath = "D:\\programming\\IDEAProject\\springboot-study\\sp06-file\\src\\main\\resources\\static\\File";
System.out.println(realPath);
File file = new File(realPath, fileName);
if (file.exists()) {
response.addHeader("Content-Disposition",
"attachment;fileName=" + fileName);// 设置文件名,默认同名
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return null;
}
}
5、MyMvcConfig.java
主要是配置了视图跳转和虚拟路径
需要调用服务器以外的资源时必须使用虚拟路径,否则前端是访问不到图片的
package com.jiyu.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
//视图跳转
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("index.html").setViewName("index");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//配置server虚拟路径,handler为前台访问的目录,locations为files相对应的本地路径
registry.addResourceHandler("/test/**").addResourceLocations("file:D:\\test\\");
}
}