标签
文件操作
字数
999 字
阅读时间
5 分钟
一、文件下载
访问资源时响应头如果没有设置 Content-Disposition,浏览器默认按 照 inline 值进行处理(inline 能显示就显示,不能显示就下载.)
只需要修改响应头中 Context-Disposition=”attachment;filename=文件名”(attachment 下载,以附件形式下载. filename=值就是下载时显示的下载文件名 )
1.1 实现步骤
导入jar包
xmlcommons-fileupload-1.3.1 commons-io-2.2在 jsp 中添加超链接,设置要下载文件
html<!-- 需要在 springmvc 中放行静态资源 files 文件夹 --> <a href="download?fileName=a.rar">下载</a>编写控制器方法
java@RequestMapping("download") public void download(String fileName,HttpServletResponse res,HttpServletRequest req) throws IOException{ //设置响应流中文件进行下载 res.setHeader("Content-Disposition", "attachment;filename="+fileName); //把二进制流放入到响应体中. ServletOutputStream os = res.getOutputStream(); String path = req.getServletContext().getRealPath("files"); System.out.println(path); File file = new File(path, fileName); byte[] bytes = FileUtils.readFileToByteArray(file); os.write(bytes); os.flush(); os.close(); }
java
/**
* 通用下载请求
* 方法见工具类
*
* @param fileName 文件名称
* @param delete 是否删除
*/
@GetMapping("common/download")
public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
try {
//检查文件是否可下载
if (!FileUtils.checkAllowDownload(fileName)) {
throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
}
String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
//配置的下载路径
String filePath = RuoYiConfig.getDownloadPath() + fileName;
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
FileUtils.setAttachmentResponseHeader(response, realFileName);
FileUtils.writeBytes(filePath, response.getOutputStream());
if (delete) {
FileUtils.deleteFile(filePath);
}
} catch (Exception e) {
log.error("下载文件失败", e);
}
}保存文件:
java
// 允许上传的格式
private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",".jpeg", ".gif", ".png"};
public PicUploadResult upload(MultipartFile uploadFile) {
// 校验图片格式
boolean isLegal = false;
for (String type : IMAGE_TYPE) {
if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),
type)) {
isLegal = true;
break;
}
}
// 封装Result对象,并且将文件的byte数组放置到result对象中
PicUploadResult fileUploadResult = new PicUploadResult();
if (!isLegal) {
fileUploadResult.setStatus("error");
return fileUploadResult;
}
// 文件新路径
String fileName = uploadFile.getOriginalFilename();
String filePath = getFilePath(fileName);
// 生成图片的绝对引用地址
String picUrl = StringUtils.replace(StringUtils.substringAfter(filePath,
"F:\\code\\itcast-haoke\\haoke-upload"),
"\\", "/");
fileUploadResult.setName("http://image.haoke.com" + picUrl);
File newFile = new File(filePath);
// 写文件到磁盘
try {
uploadFile.transferTo(newFile);
} catch (IOException e) {
e.printStackTrace();
//上传失败
fileUploadResult.setStatus("error");
return fileUploadResult;
}
fileUploadResult.setStatus("done");
fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
return fileUploadResult;
}
private String getFilePath(String sourceFileName) {
String baseFolder = "F:\\code\\itcast-haoke\\haoke-upload" + File.separator
+ "images";
Date nowDate = new Date();
// yyyy/MM/dd
String fileFolder = baseFolder + File.separator + new
DateTime(nowDate).toString("yyyy")
+ File.separator + new DateTime(nowDate).toString("MM") +
File.separator
+ new DateTime(nowDate).toString("dd");
File file = new File(fileFolder);
if (!file.isDirectory()) {
// 如果目录不存在,则创建目录
file.mkdirs();
}
// 生成新的文件名
String fileName = new DateTime(nowDate).toString("yyyyMMddhhmmssSSSS")
+ RandomUtils.nextInt(100, 9999) + "." +
StringUtils.substringAfterLast(sourceFileName, ".");
return fileFolder + File.separator + fileName;
}
}java
/**
* 通用上传请求
*/
@PostMapping("/common/upload")
public AjaxResult uploadFile(MultipartFile file) throws Exception {
try {
// 上传文件路径
String filePath = RuoYiConfig.getUploadPath();
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
//获取路径
HttpServletRequest request = ServletUtils.getRequest();
String url = getDomain(request) + fileName;
AjaxResult ajax = AjaxResult.success();
ajax.put("fileName", fileName);
ajax.put("url", url);
return ajax;
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}
public static String getDomain(HttpServletRequest request) {
StringBuffer url = request.getRequestURL();
String contextPath = request.getServletContext().getContextPath();
return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
}二、文件上传
- 基于 apache 的 commons-fileupload.jar 完成文件上传
- MultipartResovler 作用:
- 把客户端上传的文件流转换成 MutipartFile 封装类.
- 通过 MutipartFile 封装类获取到文件流
- 表单数据类型分类
- 在
<form>的 enctype 属性控制表单类型 - 默认值 application/x-www-form-urlencoded,普通表单数据.(少 量文字信息)
- text/plain 大文字量时使用的类型.邮件,论文
- multipart/form-data 表单中包含二进制文件内容.
- 在
2.1 实现步骤
导入jar包 jsp页面编写
html<form action="upload" enctype="multipart/form-data" method="post"> 姓名:<input type="text" name="name"/><br/> 文件:<input type="file" name="file"/><br/> <input type="submit" value="提交"/> </form>配置 springmvc.xml
xml<!-- MultipartResovler 解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.Comm onsMultipartResolver"> <property name="maxUploadSize" value="50"></property> </bean> <!-- 异常解析器 --> <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.Simple MappingExceptionResolver"> <property name="exceptionMappings"> <props> <propkey="org.springframework.web.multipart.MaxUploadSizeExceededException">/error.jsp</prop> </props> </property> </bean>编写控制层
java//MultipartFile 对象名必须和<input type=”file”/>的 name 属性值相同 @RequestMapping("upload") public String upload(MultipartFile file,String name) throws IOException{ String fileName = file.getOriginalFilename(); String suffix = fileName.substring(fileName.lastIndexOf(".")); //判断上传文件类型 if(suffix.equalsIgnoreCase(".png")){ String uuid = UUID.randomUUID().toString(); FileUtils.copyInputStreamToFile(file.getInputStream (), new File("E:/"+uuid+suffix)); return "/index.jsp"; }else{ return "error.jsp"; } }
三、SpringBoot配置
在springboot 的application.properties中添加
properties
## 设置单个上传文件的大小
spring.http.multipart.maxFileSize=200MB
## 设置一次请求上传文件的总容量
spring.http.multipart.maxRequestSize=200MB