springboot业务功能实战(十五)以流的方式对文件上传下载
【摘要】
java
@Controllerpublic class FileController { @RequestMapping(value = "/fileuploads") public String toFileUpload() { return "fileupload"; } @Request...
- java
-
@Controller
-
public class FileController {
-
-
@RequestMapping(value = "/fileuploads")
-
public String toFileUpload() {
-
return "fileupload";
-
}
-
-
@RequestMapping(value = "/fileupload")
-
public String fileUpload(@RequestParam(value = "file") List<MultipartFile> files, HttpServletRequest request) {
-
String msg = "";
-
// 判断文件是否上传
-
if (!files.isEmpty()) {
-
// 设置上传文件的保存目录
-
String basePath = request.getServletContext().getRealPath("/upload/");
-
// 判断文件目录是否存在
-
File uploadFile = new File(basePath);
-
if (!uploadFile.exists()) {
-
uploadFile.mkdirs();
-
}
-
for (MultipartFile file : files) {
-
String originalFilename = file.getOriginalFilename();
-
if (originalFilename != null && !originalFilename.equals("")) {
-
try {
-
// 对文件名做加UUID值处理
-
originalFilename = UUID.randomUUID() + "_" + originalFilename;
-
file.transferTo(new File(basePath + originalFilename));
-
} catch (IOException e) {
-
e.printStackTrace();
-
msg = "文件上传失败!";
-
}
-
} else {
-
msg = "上传的文件为空!";
-
}
-
}
-
msg = "文件上传成功!";
-
} else {
-
msg = "没有文件被上传!";
-
}
-
request.setAttribute("msg", msg);
-
return "chatroom";
-
}
-
-
@ExceptionHandler(MaxUploadSizeExceededException.class)
-
public String handException(MaxUploadSizeExceededException e, HttpServletRequest request) {
-
// System.out.println("我捕获了异常");
-
request.setAttribute("msg", "文件超过了指定大小,上传失败!");
-
return "fileupload";
-
}
-
-
-
@RequestMapping(value = "/filedownload")
-
public String toFileDownload(HttpServletRequest request) {
-
return "filedownload";
-
}
-
-
@RequestMapping(value = "/fileList")
-
@ResponseBody
-
public String fileList(HttpServletRequest request) {
-
String baseDir = request.getServletContext().getRealPath("/upload");
-
File baseFile = new File(baseDir);
-
List<String> fileList = null;
-
if (baseFile.exists()) {
-
File[] files = baseFile.listFiles();
-
fileList = new ArrayList<>(files.length);
-
for (File file : files) {
-
fileList.add(file.getName());
-
}
-
}
-
// System.out.println(fileList.toString());
-
String json = JSON.toJSONString(fileList);
-
return json;
-
}
-
-
-
@RequestMapping(value = "/download")
-
public ResponseEntity<byte[]> fileDownload(String filename, HttpServletRequest request) throws IOException {
-
String path = request.getServletContext().getRealPath("/upload/");
-
File file = new File(path + filename);
-
System.out.println("转码前" + filename);
-
filename = this.getFilename(request, filename);
-
System.out.println("转码后" + filename);
-
// 设置响应头通知浏览器下载
-
HttpHeaders headers = new HttpHeaders();
-
// 将对文件做的特殊处理还原
-
filename = filename.substring(filename.indexOf("_") + 1);
-
headers.setContentDispositionFormData("attachment", filename);
-
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
-
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
-
}
-
-
// 根据不同的浏览器进行编码设置,返回编码后的文件名
-
public String getFilename(HttpServletRequest request, String filename) throws UnsupportedEncodingException {
-
String[] IEBrowerKeyWords = {"MSIE", "Trident", "Edge"};
-
String userAgent = request.getHeader("User-Agent");
-
for (String keyword : IEBrowerKeyWords) {
-
if (userAgent.contains(keyword)) {
-
return URLEncoder.encode(filename, "UTF-8");
-
}
-
}
-
return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
-
}
-
-
-
}
- js
-
$(function(){
-
var targer = $("#main2")
-
$.ajax({
-
url: "fileList",
-
dataType: "json",
-
success: function (data) {
-
for (var i in data) {
-
var a = $("<a></a><br>").text(data[i].substring(data[i].indexOf("_")+1))
-
a.attr("href", "${pageContext.request.contextPath}/download?filename="+encodeURIComponent(data[i]))
-
targer.append(a)
-
alert(targer)
-
}
-
}
-
})
-
}
-
function check() {
-
var file = document.getElementById("file");
-
if (file.value == "") {
-
alert("上传的文件为空")
-
return false;
-
}
-
return true;
-
}
- jsp
-
<div id="main" style="width:500px; margin: 0 auto;">
-
<form action="fileupload" method="post" enctype="multipart/form-data" onsubmit="return check()">
-
<input type="file" name="file" id="file" multiple="multiple"><br>
-
<input type="submit" value="上传">
-
</form>
-
</div>
-
-
<div id="main2" style="width:500px; margin: 0 auto;">
-
-
</div>
文章来源: baocl.blog.csdn.net,作者:小黄鸡1992,版权归原作者所有,如需转载,请联系作者。
原文链接:baocl.blog.csdn.net/article/details/101749711
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)