菜品管理业务开发
一、文件上传下载
文件上传介绍
文件上传(upload),是指将本地图片、视频、音频等文件上传到服务器上,可以供其他用户浏览或下载的过程。文件上传在项目中应用广泛。文件上传时,对页面的form表单有如下要求:
method="post" 采用post方式提交数据
enctype="multipart/form-data" 采用multipart格式上传文件
type="file" 使用input的file控件上传
目前,一些前端组件也提供了相应的上传组件,但是底层原理还是基于form表单的文件上传。
例如:ElementUI提供的upload上传组件:
服务端要接收客户端页面上传的文件,通常都会使用Apache的两个组件:
commons-fileupload
commons-io
Spring框架在spring-web包中对文件上传进行了封装,大大简化了服务端代码,只需要在controller的方法中声明一个MultipartFile类型的参数即可接收上传的文件,例如:
文件下载介绍
文件下载,是指将文件从服务器传输到本地计算机的过程。
通过浏览器进行文件下载,通常有两种表现形式:
以附件形式下载,弹出保存对话框,将文件保存到指定磁盘目录;
直接在浏览器中打开。
通过浏览器进行文件下载,本质上就是服务端将文件以流的形式写回浏览器的过程。
文件上传代码实现
文件上传,页面端可以使用ElementUI提供的上传组件。
前端页面upload.html
文件上传下载controller类CommonController
package com.huangzx.reggie.controller;
import com.huangzx.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
* 文件上传与下载
*/
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
@Value("${reggie.path}")
private String basePath;
/**
* 文件上传
* @param file
* @return
*/
@PostMapping("/upload")
public R<String> upload(MultipartFile file){ //与Form Data中的name必须一致
//file是一个临时文件,需要转存到指定位置,否则本次请求完成后临时文件会删除
log.info(file.toString());
String originalFilename = file.getOriginalFilename(); //获得上传文件的文件名
String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); //获得上传文件的后缀名,包括"."
//使用UUID重新生成文件名,防止文件名重复上传时覆盖
String fileName = UUID.randomUUID().toString() + suffix;
//创建一个目录对象
File dir = new File(basePath);
//如果目录不存在,则创建目录
if(!dir.exists()){
dir.mkdirs();
}
try {
//将临时文件加载到指定位置
file.transferTo(new File(basePath + fileName));
} catch (IOException e) {
e.printStackTrace();
}