单文件上传
@PostMapping("/uploadfile")
@ApiOperation(notes = "教师上传教学资料",value = "传入文件")
@ResponseBody
@CrossOrigin
public Re uploadfile(@RequestParam(value="file") MultipartFile file,HttpServletRequest httpServletRequest){
if (file.isEmpty()) {
return Re.error().message("上传失败,请选择文件");
}
//获取文件名
String fileName = file.getOriginalFilename();
//获取后缀
String substring = fileName.substring(fileName.lastIndexOf("."));
//设置文件存储路径
String filePath = "D:/temp/";
File dest = new File(filePath + fileName);
//检测是否存在该目录
if (!dest.getParentFile().exists()){
dest.getParentFile().mkdirs();
}
try{
file.transferTo(dest);
}catch (Exception e){
return Re.error().message("上传失败");
}
return Re.ok().message("上传成功");
}
多文件上传
public class FileController {
/**
* 多文件上传流程
* 1.前端上传多个文件
* 2.后台使用请求对象(MultipartHttpServletRequest)接收整个请求流
* 3.获取MultipartFile集合
* 4.定义缓冲字节输出流
* 5.遍历MultipartFile集合
* 6.获取每一个MultipartFile对象
* 7.定义上传路径
* 8.判断上传文件是否为空(也就是没有上传)
* 9.如果不为空,则通过缓冲字节输出流写入到上传路径
*/
@PostMapping("batchUpload")
public String batchUpload(MultipartHttpServletRequest request){
List<MultipartFile> files = request.getFiles("file");
MultipartFile file = null;
BufferedOutputStream stream = null;
for (int i = 0; i < files.size(); i++) {
file = files.get(i);
String filePath = "f:/upload/";
if (!file.isEmpty()){
try {
byte[] bytes = file.getBytes();
stream = new BufferedOutputStream(new FileOutputStream(new File(filePath+file.getOriginalFilename())));
stream.write(bytes);
stream.close();
} catch (IOException e) {
stream = null;
return "第"+i+"个文件上传失败:"+e.getMessage();
}
}else {
return "第"+i+"个文件上传失败因为文件为空";
}
}
return "上传成功";
}
}
文件下载
@RestController
@Slf4j
public class FileController {
@GetMapping("/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
String fileName = "boss.jpg";// 文件名
if (fileName != null) {
//设置文件路径
File file = new File("f:/upload/boss.jpg");
//File file = new File(realPath , fileName);
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
return "下载成功";
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return "下载失败";
}
}
VUE+Springboot
package com.evaluation.tcvl.controller;
import com.evaluation.common.result.Re;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@RestController
@RequestMapping("/file")
@Api(value = "文件操作", tags = "文件接口")
public class FileController {
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
//在文件操作中,不用/或者\最好,推荐使用File.separator
private final static String fileDir="files";
// private final static String rootPath = System.getProperty("user.home")+ File.separator+fileDir+File.separator;
private final static String rootPath = "D:"+ File.separator+"temp"+File.separator;
@ApiOperation(notes = "教师上传教学资料",value = "传入文件")
@PostMapping("/upload")
public Object uploadFile(@RequestParam("file") MultipartFile[] multipartFiles, final HttpServletResponse response, final HttpServletRequest request){
File fileDir = new File(rootPath);
if (!fileDir.exists() && !fileDir.isDirectory()) {
fileDir.mkdirs();
}
try {
if (multipartFiles != null && multipartFiles.length > 0) {
for(int i = 0;i<multipartFiles.length;i++){
try {
//以原来的名称命名,覆盖掉旧的
String storagePath = rootPath+multipartFiles[i].getOriginalFilename();
logger.info("上传的文件:" + multipartFiles[i].getName() + "," + multipartFiles[i].getContentType() + "," + multipartFiles[i].getOriginalFilename()
+",保存的路径为:" + storagePath);
Streams.copy(multipartFiles[i].getInputStream(), new FileOutputStream(storagePath), true);
//或者下面的
// Path path = Paths.get(storagePath);
//Files.write(path,multipartFiles[i].getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
return Re.error().message("上传失败");
}
return Re.ok().message("上传成功!");
}
/**
* http://localhost:8080/file/download?fileName=新建文本文档.txt
* @param fileName
* @param response
* @param request
* @return
*/
@ApiOperation(value = "下载教学资料")
@GetMapping("/download")
public Object downloadFile(@RequestParam String fileName, final HttpServletResponse response, final HttpServletRequest request){
OutputStream os = null;
InputStream is= null;
try {
// 取得输出流
os = response.getOutputStream();
// 清空输出流
response.reset();
response.setContentType("application/x-download;charset=GBK");
response.setHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("utf-8"), "iso-8859-1"));
//读取流
File f = new File(rootPath+fileName);
is = new FileInputStream(f);
if (is == null) {
logger.error("下载附件失败,请检查文件“" + fileName + "”是否存在");
return Re.error().message("下载附件失败,请检查文件“" + fileName + "”是否存在");
}
//复制
IOUtils.copy(is, response.getOutputStream());
response.getOutputStream().flush();
} catch (IOException e) {
return Re.error().message("下载附件失败,error:"+e.getMessage());
}
//文件的关闭放在finally中
finally
{
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}