SpringBoot 文件上传(可配置文件上传路径)
1. 在
中配置文件上传路径 ,上传文件大小
application:
#版本
version: 1.0.0
#文件上传路径
profile: D:/profile/
spring:
servlet:
multipart:
max-file-size: 30MB
max-request-size: 30MB
2. 配置MVC,使文件上传路径可以被项目访问到
加载配置路径
@Component
@ConfigurationProperties(prefix = "application")
public class MyConfig{
/**
* 版本
*/
private String version;
/**
* 上传文件路径
*/
private static String profile;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public static String getProfile() {
return profile;
}
public void setProfile(String profile) {
Twlyyx.profile = profile;
}
}
MVC配置使http://IP:端口号/${-path}/profile/图片路径
可以访问到配置的文件夹
@Configuration
public class ResourceConfig implements WebMvcConfigurer {
//图片保存路径
public static final String PIC_PATH = "/profile/";
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/** 图片传路径 */
registry.addResourceHandler("/profile/**").addResourceLocations("file:" + MyConfig.getProfile());
}
3. 上传文件工具类
网上有很多,这里就不写了
4. 前端上传
<form method="post" id="bannerForm">
<img id="preview" width="200px" height="200px" onclick="show()" />
<input type="file" title="上传图片" name="file" id="input_file" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" onchange="imgPreview(this)">
<%--其他表单信息--%>
<input type="text" name="info">
<button type="submit">提交</button>
</form>
<script>
//大图预览
function show() {
var img = new Image();
img.src = $("#preview").attr("src");
var imgHtml = "<img src='" + img.src + "' />";
//捕获页
layer.open({
type: 1,
shade: false,
title: false, //不显示标题
area: ['600px', '500px'],
// area: [ + 'px', +'px'],
content: imgHtml, //捕获的元素,注意:最好该指定的元素要存放在body最外层,否则可能被其它的相对元素所影响
cancel: function () {
//('捕获就是从页面已经存在的元素上,包裹layer的结构', { time: 5000, icon: 6 });
}
});
}
//上传预览
function imgPreview(fileDom) {
//判断是否支持FileReader
if (window.FileReader) {
var reader = new FileReader();
} else {
alert("您的设备不支持图片预览功能,如需该功能请升级您的设备!");
}
//获取文件
var file = fileDom.files[0];
var imageType = /^image\//;
//是否是图片
if (!imageType.test(file.type)) {
alert("请选择图片!");
return;
}
//读取完成
reader.onload = function (e) {
//获取图片dom
var img = document.getElementById("preview");
//图片路径设置为读取的图片
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
</script>
Ajax提交含有文件的图片
//使用var form = $("#bannerForm");不生效
var form = document.querySelector("#bannerForm");
var formData = new FormData(form);
// ("file", $('#input_file')[0].files[0]);
$.ajax({
url: "${ctx}/save",
type: 'POST',
cache: false, //上传文件不需要缓存
data: formData,
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success:function (data) {
if (data.code == 0) {
layer.alert('添加成功!', function () {
window.location.href = '${ctx}/market/list';
});
} else {
layer.msg("失败", {icon: 2, time: 1000});
}
}
});
5. 后台接收
@ResponseBody
@RequestMapping("/save")
public Object save(Info info, MultipartFile file) {
···
···
···
return ···;
}