上传
前端:form表单要求如下:1.必须采用post的请求方式 2.必须使用file属性的input 3.表单的enctype属性必须是multipart
后端:如果服务中可能接收到文件流,那么直接在Controller具体服务函数形参中接收一个MultiPartFile对象即可
但是!!!!MultiPartFile对象的名字必须和html标签中name的属性要一致,否则找不到
下载
作为附件下载或者直接在浏览器中打开
package com.mtj.controller;
import com.mtj.generally.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
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.FileInputStream;
import java.util.Arrays;
import java.util.UUID;
/**
* 处理文件的上传和下载
*/
@RestController
@RequestMapping(value = "/common")
@Slf4j
public class CommonController {
private String basePath = new String("c:\\intel\\");
/**
* 文件上传
*
* @param file
* @return
*/
@PostMapping(value = "/upload")
private Result upload(MultipartFile file, HttpServletRequest request) {
log.info("File upload is Loading..." + file.toString());
//使用UUID随机生成文件名防止重复
String fileName = UUID.randomUUID().toString();
//动态的获取文件的后缀名,注意这个正则中的.得用\\.来表示
String[] split = file.getOriginalFilename().split("\\.");
String LastName = split[split.length - 1];
String finalName = fileName + "." + LastName;
log.info("finalName:" + finalName);
try {
file.transferTo(new File(basePath + finalName));
} catch (Exception e) {
log.error(e.getMessage());
}
return new Result(1, finalName, "上传成功");
}
/**
* 文件下载
* @param response
* @param name
*/
@GetMapping(value = "/download")
private void download(HttpServletResponse response, String name) {
try {
//从本地获取对应图片
FileInputStream fin = new FileInputStream(basePath + name);
//获取写入response中
ServletOutputStream fou = response.getOutputStream();
fou.write(fin.readAllBytes());
} catch (Exception e) {
log.error(e.getMessage());
}
}
}