一、element-plus前端
使用element-plus前端vue框架,能够很大幅度简化前端代码。<el-upload></el-upload>为上传标签。属性如下:
- action:上传服务端地址。
- :show-file-list:是否展示上传文件列表。
- :on-success:上传成功后触发的函数。
- :before-upload:上传前触发的函数。
<el-upload
class="avatar-uploader"
action="http://localhost:8080/upload"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
<img v-if="imageUrl" width="50px" height="50px" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<img>用于显示上传后的图片,<i>用于显示上传前的内容。JS和CSS代码如下:
<script setup>
import {ref} from "vue";
// img图片的地址
let imageUrl = ref('');
// 上传成功后触发,在img中显示上传的图片,resp为后端上传方法的返回值
const handleAvatarSuccess = (resp) => {
imageUrl.value = `http://localhost:8080/download?name=${resp}`
};
// 上传前触发,可用于检验上传文件的类型、大小限制等。
const beforeAvatarUpload = (file) => {
/*
const isPNG = file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isPNG) {
this.$message.error('上传头像图片只能是 PNG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
*/
return true;
}
</script>
<style scoped>
/*上传图片样式:*/
.avatar-uploader .el-upload {
border: dashed 2px #d8dde3 !important;
border-radius: 4px !important;
background: #fcfcfc;
}
.avatar-uploader .avatar-uploader-icon {
background: #fcfcfc;
}
.avatar-uploader .el-icon-plus:before {
content: "上传图片" !important;
font-size: 16px;
color: #000;
}
</style>
二、服务端上传
后端使用MultipartFile对象接收上传文件,并通过该对象获取上传的各种信息。
@PostMapping("/upload")
public String upload(MultipartFile file) {
//原始文件名
String originalFilename = file.getOriginalFilename();
//获取原文件的类型
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//使用UUID重新生成文件名,防止文件名称重复造成文件覆盖
String fileName = UUID.randomUUID() + suffix;
//创建一个目录对象,用于存储上传文件
File dir = new File("F:\\images\\");
//判断当前目录是否存在:目录不存在,需要创建
if (!dir.exists()) dir.mkdirs();
try {
//保存文件到指定目录
file.transferTo(new File("F:\\images\\" + fileName));
} catch (IOException e) {
e.printStackTrace();
}
return fileName;
}
三、服务端下载
@GetMapping("/download")
public void download(String name, HttpServletResponse response) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//输入流,通过输入流读取文件内容
bis = new BufferedInputStream(new FileInputStream("F:\\images\\" + name));
//输出流,通过输出流将文件写回浏览器
bos = new BufferedOutputStream(response.getOutputStream());
// 设置相应类型
response.setContentType("image/png");
int i = 0;
while ((i = bis.read()) != -1) {
bos.write(i);
}
bos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bos != null) bos.close();
if (bis != null) bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}