介绍
- 文件的上传是指将本地图片、视频、音频等以文件的形式上传到服务器上,可供其他用户进行浏览下载的过程
文件上传
要求
- 我们使用文件上传都是基于form表单的方式上传的,但是对form表单有硬性条件需要满足。
- method = “post” 表单需要采用post方式提交数据
- enctype = “multipart/form-data” 采用multipart格式上传文件
- type = “file” 使用input标签的file控件进行上传
比如
<form method="post" enctype="multipart/form-data">
<input name="myFile" type="file"/>
<input name="submit" value="提交"/>
</form>
后端接收上传的文件
- spring框架在spring-web包中对文件上传进行了封装,大大简化了服务端代码,我们只需要在Controller方法中声明一个MultipartFile类型的参数即可接收到上传的文件
注意: 参数类型必须是MultipartFile类型的,且参数名称最好和input对应的name属性保持一致,如果不一致就需要使用@RequestPart(“名称”)进行修改
即:
如果前端input是这样写的
<input type="file" name="myfile">
则后端控制器参数名应该也叫myfile
@RequestMapping()
public void upload(MultipartFile myfile){
}
或者使用@RequestPart注解进行改名
@RequestMapping()
public void upload(@RequestPart("myfile")MultipartFile file){
}
- 现在控制器中接收到的file是一个临时文件,会临时存在一个地方,我们需要进行转存到指定位置,否则本次请求结束之后临时文件就会被自动删除
转存的方式:使用MultipartFile中的方法transferTo(new File("指定转存的位置"));
@RequestMapping()
public void upload(@RequestPart("myfile")MultipartFile file){
//这里我将上传的文件转存到D盘下
file.transferTo(new File("D:\\))
}
完整的方法:
@RestController
@RequestMapping("/common")
public class CommonController {
@Value("${picture.url}")
private String baseUrl;
@PostMapping("/upload")
public Result<String> upload(MultipartFile file){
//获取源文件的名字
String originalFilename = file.getOriginalFilename();
//获取源文件的后缀 ,通过.来分割
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//新的文件名 = uuid + 源文件后缀格式
String fileName = UUID.randomUUID().toString() + suffix;
System.out.println(fileName);
File dirPath = new File(baseUrl);
//文件路径不存在会自动创建
if(!dirPath.exists()){
dirPath.mkdirs();
}
try {
//将上传的文件永久的存储到本地,baseUrl是在application中配置的,通过@Value注入进来的
file.transferTo(new File(baseUrl+fileName));
} catch (IOException e) {
e.printStackTrace();
}
return Result.success(fileName);
}
文件下载
@GetMapping("/download")
public void download(String name, HttpServletResponse response){
//文件输入流,用于从文件保存的位置读取指定的文件
FileInputStream fileInputStream = null;
//输出流,将文件回显到网页上进行显示
ServletOutputStream outputStream = null;
try {
byte[] bytes = new byte[1024];
int length = 0;
fileInputStream = new FileInputStream(baseUrl+name);
outputStream = response.getOutputStream();
while ((length=fileInputStream.read(bytes))!=-1){
outputStream.write(bytes,0,length);
}
outputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}