SpringBoot 文件上传(可配置文件上传路径)

SpringBoot 文件上传(可配置文件上传路径)

1. 在application.yml中配置文件上传路径 ,上传文件大小

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:端口号/${server.context-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: [img.width + 'px', img.height+'px'],
            content: imgHtml, //捕获的元素,注意:最好该指定的元素要存放在body最外层,否则可能被其它的相对元素所影响
            cancel: function () {
                //layer.msg('捕获就是从页面已经存在的元素上,包裹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);
                // formData.append("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 ···; 
 }
  • 8
    点赞
  • 67
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tcoding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值