SpringMVC-文件下载与上传
1.文件下载
2.文件上传
1).导入相关jar包
2).在springmvc.xml配置文件中装配MultpartResovler
<!--上传文件配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--设置字符集的编码-->
<property name="defaultEncoding" value="UTF-8"/>
<!--最大文件上传尺寸-->
<property name="maxUploadSize" value="102400"/>
</bean>
代码示例:
前端请求界面:
<%--文件下载--%>
<a href="${pageContext.request.contextPath}/download/1.png">下载1.png</a>
<a href="${pageContext.request.contextPath}/download/图片.png">下载 图片.png</a>
<%--文件上传--%>
<hr>
<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" value="上传">
</form>
后台前端控制界面:
package com.helong.web.controller;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;
@Controller
public class MyController {
//使用下面这种方式的时候就可以获取文件的后缀名了
@RequestMapping("/download/{filename:.+}")
public ResponseEntity download(@PathVariable String filename, HttpSession httpSession) throws Exception {
System.out.println(filename);
//1.获取文件的路径
ServletContext servletContext = httpSession.getServletContext();
String realPath = servletContext.getRealPath("/download/" + filename);
//2.把文件读到程序里面
InputStream io = new FileInputStream(realPath);
byte[] body = new byte[io.available()];
io.read(body);
//3.创建响应头
HttpHeaders httpHeaders = new HttpHeaders();
/*解决中文文件名下载时不能显示文件名的问题*/
filename = URLEncoder.encode(filename,"utf-8");
/*告诉浏览器以辅件的形式进行下载*/
httpHeaders.add("Content-Disposition","attachment;filename="+filename);
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(body, httpHeaders, HttpStatus.OK);
return responseEntity;
}
//文件上传
@RequestMapping("upload")
public String upload(@RequestParam("file") CommonsMultipartFile file,HttpSession session) throws IOException {
System.out.println(file.getContentType());/*文件类型*/
System.out.println(file.getOriginalFilename());/*文件名称*/
System.out.println(file.getSize());/*获取文件大小*/
System.out.println(file.getName());/*获取文件对应的属性名称*/
//确定文件上传的路径
ServletContext servletContext = session.getServletContext();
String realPath = servletContext.getRealPath("/upload");
//变成程序当中的路径
File uploadPath = new File(realPath);
if(!uploadPath.exists()){
//如果路径不存在,创建一个新文件夹
uploadPath.mkdirs();
}
//确认最终的路径 /文件夹/文件名 工程的名称/upload/java.png
String filename = file.getOriginalFilename();
//将原来的路径重新复制
uploadPath = new File(uploadPath + "/" + filename);
//开始上传
file.transferTo(uploadPath);
return "result.jsp";
}
}
3.多文件上传(使用WebUploader由百度提供)
1).将文件引入对应位置
2).在springmvc.xml文件中设置允许静态文件访问
<!--开启静态文件访问权限-->
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/css/**" location="/css/"/>
3).前端的上传界面示例:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>WebUploader文件上传简单示例</title>
<%--引入css样式--%>
<link href="${pageContext.request.contextPath}/css/webuploader.css" rel="stylesheet" type="text/css"/>
<script src="${pageContext.request.contextPath}/js/jquery-3.4.1.js" type="text/javascript"></script>
<%--引入文件上传插件--%>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/webuploader.js"></script>
<script type="text/javascript">
$(function () {
var $ = jQuery,
$list = $('#fileList'),
//优化retina, 在retina下这个值是2
ratio = window.devicePixelRatio || 1,
// 缩略图大小
thumbnailWidth = 100 * ratio,
thumbnailHeight = 100 * ratio,
// Web Uploader实例uploader;
// 初始化Web Uploader
uploader = WebUploader.create({
// 自动上传。
auto: false,
// swf文件路径
swf: '${pageContext.request.contextPath}/js/Uploader.swf',
// 文件接收服务端。
server: '${pageContext.request.contextPath}/upload',
fileVal: 'file',
threads: '30', //同时运行30个线程传输
fileNumLimit: '10', //文件总数量只能选择10个
// 选择文件的按钮。可选。
pick: {
id: '#filePicker', //选择文件的按钮
multiple: true //允许可以同时选择多个图片
},
//图片质量,只有type为`image/jpeg`的时候才有效。
quality: 100,
//限制传输文件类型,accept可以不写 (用于显示文件类型筛选)
/* accept: {
title: 'Images',//描述
extensions: 'gif,jpg,jpeg,bmp,png,zip',//类型
mimeTypes: 'image/*'//mime类型
} */
});
// 当有文件添加进来的时候,创建img显示缩略图使用
uploader.on('fileQueued', function (file) {
var $li = $(
'<div id="' + file.id + '" class="file-item thumbnail">' +
'<img>' +
'<div class="info">' + file.name + '</div>' +
'</div>'
),
$img = $li.find('img');
// $list为容器jQuery实例
$list.append($li);
// 创建缩略图
// 如果为非图片文件,可以不用调用此方法。
// thumbnailWidth x thumbnailHeight 为 100 x 100
uploader.makeThumb(file, function (error, src) {
if (error) {
$img.replaceWith('<span>不能预览</span>');
return;
}
$img.attr('src', src);
}, thumbnailWidth, thumbnailHeight);
});
// 文件上传过程中创建进度条实时显示。
// uploadProgress事件:上传过程中触发,携带上传进度。
// file文件对象 percentage传输进度 Number类型
uploader.on('uploadProgress', function (file, percentage) {
console.log(percentage);
});
// 文件上传成功时候触发,给item添加成功class,
// 用样式标记上传成功。
// file:文件对象,
// response:服务器返回数据
uploader.on('uploadSuccess', function (file, response) {
$('#' + file.id).addClass('upload-state-done');
//console.info(response);
$("#upInfo").html("<font color='red'>" + response._raw + "</font>");
});
// 文件上传失败
// file:文件对象 ,
// code:出错代码
uploader.on('uploadError', function (file, code) {
var $li = $('#' + file.id),
$error = $li.find('div.error');
// 避免重复创建
if (!$error.length) {
$error = $('<div class="error"></div>').appendTo($li);
}
$error.text('上传失败!');
});
// 不管成功或者失败,
// 文件上传完成时触发。
// file: 文件对象
uploader.on('uploadComplete', function (file) {
$('#' + file.id).find('.progress').remove();
});
//绑定提交事件
$("#btn").click(function () {
console.log("上传...");
uploader.upload(); //执行手动提交
console.log("上传成功");
});
});
</script>
<script>
var contextpath = ${pageContext.request.contextPath};
</script>
<script type="text/javascript" src=""></script>
</head>
<body style="padding:10px">
<h3>多文件上传</h3>
<!--dom结构部分-->
<div id="uploader-demo">
<!--用来存放item-->
<div id="fileList" class="uploader-list"></div>
<div id="upInfo"></div>
<div id="filePicker">选择文件</div>
</div>
<input type="button" id="btn" value="开始上传">
</body>
</html>
4).后台前端控制器的设置与单文件上传一致
转载:https://blog.csdn.net/weixin_43478300/article/details/102171120
查看评论