目录
总体介绍
文件上传
介绍
文件上传的前端需求
但是在实际的开发过程中,前端页面有关这一部分的设计通常是使用组件进行封装,例如使用element-ui在完成功能实现的基础上实现了对上传组件页面设计的优化。(底层仍然是使用post表单的方式进行发送请求)
如下:
文件上传的前端代码
具体实现上传功能的element-ui的代码如下:
<div class="addBrand-container" id="food-add-app">
<div class="container">
<el-upload class="avatar-uploader"
action="/common/upload"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeUpload"
ref="upload">
<img v-if="imageUrl" :src="imageUrl" class="avatar"></img>
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</div>
</div>
文件上传的后端需求
服务端要接收客户端页面上传的文件,通常都会使用Apache的两个组件:
Spring框架在spring-web包中对文件上传进行了封装,大大简化了服务端代码,我们只需要在Controller的方法中声明一个MultipartFile类型的参数即可接收上传的文件,例如:
关于对于文件上传的后端实现逻辑,一般是如下的实现思路:
我们给出文件上传的后端代码实现:
文件上传的后端代码
我们通过使用@Value注解从配置文件中读取文件保存路径:
@Value("${reggie.path}")
private String path;
reggie:
path: D:\img\
@PostMapping("/upload")
public R<String>upload(MultipartFile file){
log.info(file.toString());
//获取原始文件名,提取JPG
String originalFilename = file.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//生成随机文件名
String random=UUID.randomUUID().toString();
//获取新名称
String fileName=random+suffix;
//创建新名称
File file1 = new File(path);
if(!file1.exists()){
file1.mkdirs();
}
//进行转存
try {
log.info("文件路径为"+path+fileName);
file.transferTo(new File(path+fileName));
} catch (IOException e) {
throw new RuntimeException(e);
}
return R.success(fileName);
}
文件下载
介绍
前端需求
代码示例:
url展示:我们可以发现,download的url中包含了具体图片的文件名
前端代码
具体的前端代码如下:
methods: {
handleAvatarSuccess (response, file, fileList) {
this.imageUrl = `/common/download?name=${response.data}`
},
beforeUpload (file) {
if(file){
const suffix = file.name.split('.')[1]
const size = file.size / 1024 / 1024 < 2
if(['png','jpeg','jpg'].indexOf(suffix) < 0){
this.$message.error('上传图片只支持 png、jpeg、jpg 格式!')
this.$refs.upload.clearFiles()
return false
}
if(!size){
this.$message.error('上传文件大小不能超过 2MB!')
return false
}
return file
}
}
}
后端需求
后端代码
后端代码如下:
@GetMapping("/download")
public void downLoad(String name, HttpServletResponse response){
//输入流,通过提供指定位置去读取数据
try {
FileInputStream fileInputStream = new FileInputStream(new File(path + name));
//输出流,通过读取到的数据输出到浏览器中
ServletOutputStream outputStream = response.getOutputStream();
response.setContentType("image/jpeg");
//将数据通过byte字符数组进行读取
int len=0;
byte[]bytes=new byte[1024];
while((len=fileInputStream.read(bytes))!=-1){
outputStream.write(bytes,0,len);
//刷新
outputStream.flush();
}
fileInputStream.close();
outputStream.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}