目录
前台界面
上传
下载
前台代码
后台项目结构
后台主要代码
下载
调整对下载不存在文件的处理
效果
代码
附件上传、下载
附件上传、下载
package com.lxw.uploaddownload.controller;
import com.lxw.uploaddownload.common.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
@RestController
@RequestMapping("/file")
public class FileController {
@Value("${filePath}")
private String filePath;
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
//上传文件
@PostMapping("/upload")
@ResponseBody
public Response uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("fid") Integer fid, HttpServletResponse response) {
if (file.isEmpty()) {
return new Response().error("上传失败,请选择文件");
}
// 获得提交的文件名
String fileName = file.getOriginalFilename();
// 获取文件输入流
//InputStream ins = file.getInputStream();
// 获取文件类型
//String contentType = file.getContentType();
//加个时间戳,尽量避免文件名称重复
fileName = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date()) + "_" + fileName;
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest);
//logger.info("上传成功");
return new Response().success(fileName);
} catch (Exception e) {
//logger.error(e.getMessage());
return new Response().error("上传失败");
}
}
//下载文件
@GetMapping(value = "/download")
public void downloadFile(@RequestParam(name = "file_name") String fileName,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
//logger.info("download....file_name:" + fileName);
File file = new File(filePath + "/" + fileName);
if (file.exists()) { //判断文件是否存在
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
byte[] buffer = new byte[1024];
FileInputStream fis = null; //文件输入流
BufferedInputStream bis = null;
OutputStream os = null; //输出流
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
}
logger.info("----------file download" + fileName);
try {
bis.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}else{
response.setStatus(404);
}
}
}
package com.lxw.uploaddownload.controller;
import com.lxw.uploaddownload.common.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
@RestController
@RequestMapping("/file")
public class FileController {
@Value("${filePath}")
private String filePath;
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
//上传文件
@PostMapping("/upload")
@ResponseBody
public Response uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("fid") Integer fid, HttpServletResponse response) {
if (file.isEmpty()) {
return new Response().error("上传失败,请选择文件");
}
// 获得提交的文件名
String fileName = file.getOriginalFilename();
// 获取文件输入流
//InputStream ins = file.getInputStream();
// 获取文件类型
//String contentType = file.getContentType();
//加个时间戳,尽量避免文件名称重复
fileName = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date()) + "_" + fileName;
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest);
//logger.info("上传成功");
return new Response().success(fileName);
} catch (Exception e) {
//logger.error(e.getMessage());
return new Response().error("上传失败");
}
}
//下载文件
@GetMapping(value = "/download")
public void downloadFile(@RequestParam(name = "file_name") String fileName,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
//logger.info("download....file_name:" + fileName);
File file = new File(filePath + "/" + fileName);
if (file.exists()) { //判断文件是否存在
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
byte[] buffer = new byte[1024];
FileInputStream fis = null; //文件输入流
BufferedInputStream bis = null;
OutputStream os = null; //输出流
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
}
logger.info("----------file download" + fileName);
try {
bis.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}else{
response.setStatus(404);
}
}
}
Demo下载
if (file.exists()) { //判断文件是否存在
//
} else {
try {
response.setContentType("text/html; charset=UTF-8"); //转码
PrintWriter out = response.getWriter();
out.flush();
out.println("文件不存在或已经被删除!");
} catch (IOException e) {
// logger.error("下载文件出错:" + e);
}
}