文件上传和下载
程序员文章站
2022-04-30 20:13:06
...
1.文件上传前端用fileupload后端这样上传到服务器
/**
* @author zhenglong
* @Description: 巡检任务的上传
* @Date 2019/6/26 13:21
*/
@RestController
public class UploadExcelController extends HttpServlet {
@Value("${uploadexcel.file.path}")
private String uploadExcelFilePath ;
@Autowired
private TaskService taskService;
@PostMapping("/upload")
@ResponseBody
public ServerResponse upload(HttpServletRequest request, HttpServletResponse response,@RequestParam("taskId") Integer taskId) {
//如果没有任务的id直接返回
if(taskId==0 || taskId==null){
return ResponseUtil.business_error(1003, "传参数错误");
}
String saveUrl = uploadExcelFilePath;
//定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("file", "doc,docx,xls,xlsx,txt");
// 设置文件上传大小,单位kb
long maxSize = 20480;
response.setContentType("text/html; charset=UTF-8");
// 判断是否是文件上传的request
if (!ServletFileUpload.isMultipartContent(request)) {
return ResponseUtil.business_error(404, "请选择文件。");
}
//检查目录 d:\\upload
// saveUrl = "D:\\upload/";
File uploadDir = new File(saveUrl);
if (!uploadDir.isDirectory()) {
return ResponseUtil.business_error(404, "上传目录不存在。");
}
//检查目录写权限
if (!uploadDir.canWrite()) {
return ResponseUtil.business_error(400, "上传目录没有写权限。");
}
// dir:image
String dirName = request.getParameter("dir");
// 如果dirname为空,默认file
if (dirName == null) {
dirName = "file";
}
// 判断dirName是否在extMap存在
if (!extMap.containsKey(dirName)) {
return ResponseUtil.business_error(400, "目录名不正确。");
}
saveUrl += dirName + "/";
// 创建加上时间之后的文件夹
File dirFile = new File(saveUrl);
// 如果文件夹不存在,则创建
if (!dirFile.exists()) {
dirFile.mkdirs();
}
// 创建上传文件的保存的工厂
MultipartHttpServletRequest servletRequest = (MultipartHttpServletRequest) request;
// 获取上传的多个文件的名字
Iterator<String> iterator = servletRequest.getFileNames();
// 遍历名字
while (iterator.hasNext()) {
// 获取文件的名字
String fileName = iterator.next();
// 获取文件
MultipartFile file = servletRequest.getFile(fileName);
//检查文件大小
if (file.getSize() > maxSize) {
return ResponseUtil.business_error(500, "上传文件大小超过限制。");
}
//检查扩展名
String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
// 判断后缀名在对应的类型中是否存在
if (!extMap.get(dirName).contains(ext)) {
return ResponseUtil.business_error(500, "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
}
// 给文件随机一个名字
String filename = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")).toLowerCase();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = filename+ "("+df.format(new Date()) +")" + "." + ext;
// 复制内容
try {
//把文件名字存入数据库中
Boolean flag= taskService.updatePath(taskId,newFileName);
if(flag){
File uploadedFile = new File(saveUrl, newFileName);
file.transferTo(uploadedFile);
}
} catch (Exception e) {
return ResponseUtil.business_error(500, "上传文件失败。");
}
//上传文件返回的信息
HashMap<String, Object> map = new HashMap<>();
map.put("error", 0);
map.put("url", newFileName);
return ResponseUtil.success(map);
}
return null;
}
}
2文件下载,前端用location.href这样请求后台的方法即可后端代码如下
/**
* @author zhenglong
* @Description: 浏览器下载文件
* @Date 2019/6/29 19:04
*/
import com.auth0.jwt.internal.org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
@RestController
public class DownloadController {
@Value("${downloadexcel.file.path}")
private String downloadFilePath;
/**
* 文件下载的方法,需要传下载文件的名字
* @param response
* @param request
*/
@GetMapping("/download")
public void download(HttpServletResponse response, HttpServletRequest request) {
String url = downloadFilePath;
// url ="D:\\upload\\file";
String file = request.getParameter("name");
if (!StringUtils.isNotBlank(file)) {
return;
}
url +="/"+ file;
if (url != null && url != "") {
String fileName = url.substring(url.lastIndexOf("/") + 1).toLowerCase();
try {
this.prototypeDownload(new File(url), fileName, response, false,request);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* @param file 要下载的文件
* @param returnName 返回的文件名
* @param response HttpServletResponse
* @param delFlag 是否删除文件
*/
private void prototypeDownload(File file, String returnName, HttpServletResponse response, boolean delFlag,HttpServletRequest request) {
// 下载文件
FileInputStream inputStream = null;
ServletOutputStream outputStream = null;
try {
if (!file.exists()) return;
response.reset();
//设置响应类型 PDF文件为"application/pdf",WORD文件为:"application/msword", EXCEL文件为:"application/vnd.ms-excel"。
response.setContentType("application/octet-stream;charset=utf-8");
String agent =request.getHeader("USER-AGENT");
if(agent !=null && agent.indexOf("Mozilla") != -1){
//保存的文件名,必须和页面编码一致,否则乱码
returnName = response.encodeURL(new String(returnName.getBytes("utf-8"), "iso-8859-1"));
}else{
//设置响应的文件名称,并转换成中文编码
returnName = URLEncoder.encode(returnName, "UTF-8");
}
//attachment作为附件下载;inline客户端机器有安装匹配程序,则直接打开;注意改变配置,清除缓存,否则可能不能看到效果
response.addHeader("Content-Disposition", "attachment;filename=" + returnName);
//将文件读入响应流
inputStream = new FileInputStream(file);
outputStream = response.getOutputStream();
int length = 1024;
int readLength = 0;
byte buf[] = new byte[1024];
readLength = inputStream.read(buf, 0, length);
while (readLength != -1) {
outputStream.write(buf, 0, readLength);
readLength = inputStream.read(buf, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
//删除原文件
if (delFlag) {
file.delete();
}
}
}