栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot+前端实现文件(图片)上传到指定目录

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot+前端实现文件(图片)上传到指定目录

第一步
前端写html的代码

       
            
*上传图片
            //完成增加方法
            add:function (){
                let params = new FormData();
                params.append('id',this.id);
                params.append('saleId',this.saleId);
                params.append('saleName',this.saleName);
                params.append('sex',this.sex);
                 let files = $("#file")[0].files[0];
                params.append('file',files);
                let config = {
                    'Content-Type':false
                };
                axios.post('/sale/add', params,config)
                    .then(function (response) {
                        if (response.status == 200){
                            console.log(response.data);
                            //执行重定向
                            // window.location.href = response.data;
                            var index = parent.layer.getframeIndex(window.name);
                            //关闭当前页 关闭小弹窗
                            parent.layer.close(index);
                            parent.location.reload(); //刷新父页面

                        }
                    })
                    .catch(function (error) {
                        // console.log(error.data);//undefined,之前以为这样可以拿到错误信息
                        // console.log(error.response.data.rentCarTime);//可以拿到后端返回的信息
                    });

            }


后端需要导入的pom依赖

        
        
            commons-fileupload
            commons-fileupload
            1.3.1
        
#文件上传到指定项目目录
upload-path: E:/car-manager/src/main/resources/static/images/
spring:
resources:
static-locations: classpath:/static/,file:${upload-path}
spring.http.multipart.enabled=false
multipart.maxFileSize=5000KB
multipart.maxRequestSize=5000KB

controller

    @Value("${upload-path}")
    private String uploadPath;

	
	//增
    @PostMapping("/add")
    @ResponseBody
    public String saleAdd(Sale sale, FileAll fileAll) throws IOException {
        System.out.println(sale);
        System.out.println(fileAll.getFile());
        MultipartFile file = fileAll.getFile();
        if (!file.isEmpty()){
//           获得图片名字
           String filename = file.getOriginalFilename();
//           将完整路径放到一个对象里面
           String fileAlls = uploadPath+filename;
            System.out.println(uploadPath);
            System.out.println(fileAlls);
//            把图片的名字放到sale对象里面保存
           sale.setImgPath(filename);
//           保存到数据库
           saleService.save(sale);
//           保存到项目的指定文件夹
           FileUtils.copyInputStreamToFile(file.getInputStream(),new File(fileAlls));
       }
        return null;
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/337703.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号