SpringBoot+Vue.js+Element-UI实现图片上传

.vue文件,指定文件上传的接口地址




    点击上传
只能上传jpg/jpeg/png文件,且不超过500kb

这里选择图片后自动上传

这里通过element-ui的回调函数在input框中返回图片名称,这个只是为了好看一点,不加也无所谓

handleChange:function (file, fileList) {
    this.facepicUrlShow = file.name;
},

后端springboot添加依赖,我这里用的是commons.io


    commons-io
    commons-io
    2.4

后端springboot中controller层,上传文件是使用MultipartFile类

@RequestMapping(value = "/uploadfile")
    public CommonResult uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        // 文件名
        String fileName = file.getOriginalFilename();
        // 在file文件夹中创建名为fileName的文件
        assert fileName != null;
        int split = fileName.lastIndexOf(".");
        // 文件后缀,用于判断上传的文件是否是合法的
        String suffix = fileName.substring(split+1,fileName.length());
        //判断文件类型,因为我这边是图片,所以只设置三种合法格式
        String url = "";
        if("jpg".equals(suffix) || "jpeg".equals(suffix) || "png".equals(suffix)) {
            // 正确的类型,保存文件
            try {
                File path = new File(ResourceUtils.getURL("classpath:").getPath());
                File upload = new File(path.getAbsolutePath(), "upload/");
                if(!upload.exists()) {
                    upload.mkdirs();
                }
                String newName = System.currentTimeMillis() + "."+suffix;
                String homepath = "/home/upload/images";
                File savedFile = new File(upload + "/" + newName);
                file.transferTo(savedFile);
                url = savedFile.getAbsolutePath();
                System.out.println("图片上传完毕,存储地址为:"+ url);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }else {
            //错误的类型,返回错误提示

        }
        File savedFile;
        return CommonResult.success(url);
    }

这里我踩坑费了好大劲,网上上传文件的代码本地都没有问题,一旦打成jar包,在Linux服务器上运行,就会找不到文件路径

有两种办法

第一种,自己定义一个服务器上的绝对路径,我这里定义了homepath,是服务器上某个文件夹的地址,把xxxxx换成你定义的上传路径

File savedFile = new File("xxxxx" + newName);

第二种,使用相对路径,就是代码里写的,在application.properties文件中加上

默认情况下,会映射资源/** 但你可以通过spring.mvc.static-path-pattern调整该资源

#这表示只有静态资源的访问路径为/resources/**时,才会处理请求
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:upload/

表示静态资源的访问路径,我这里就放在resources/upload下面,此时本地上传文件路径就是项目/target/classes/upload

图片上传完毕,存储地址为:/Users/Arithmetic/yunprophet/target/classes/upload/1584874173552.png

如果是服务器端,路径就是

你可能感兴趣的:(springboot,java)