springboot项目打包jar后图片上传及图片路径

springboot项目打包jar后图片上传及图片路径

前端部分

<Upload name=“logo” action=“http://localhost:9001/api/phonebook/uploadPhoto” listType=“picture”
accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
maxCount={1} {…props}>
<Button icon={}>点击上传

<Form.Item
                    name="photo"
                    label="照片"
                    valuePropName="fileList"
                    getValueFromEvent={normFile}
                    extra="请上传照片"
                >
                    <Upload name="logo" action="http://localhost:9001/api/phonebook/uploadPhoto" listType="picture"
                            accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
                            maxCount={1} {...props}>
                        <Button icon={<UploadOutlined />}>点击上传</Button>
                    </Upload>
                </Form.Item>
                
  • accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG",为限制文件格式
  • maxCount={1} ,为限制文件上传数量,=1时最新的覆盖以前的
  • name=“logo” ,后端获取的名字
  • action=“http://localhost:9001/api/phonebook/uploadPhoto” ,为后端api接口,打包为jar部署后要改成对应ip

想要获取返回值,查看官方文档里的change函数,info.file.responce获取

后端部分

项目打包后的jar包都在target文件夹里面,也就是说target所在文件夹才是jar包所在的路径,所以,图片存储的位置就应该在target里面,这样在打成jar包后,就可以获取jar包所在目录,实现上面分析的功能

 @RequestMapping("/uploadPhoto")
    @ResponseBody
    public Map<Integer,String> uploadPhoto(@RequestParam("logo") MultipartFile pic) throws IOException {
        /*
         * 编码为字符串*/
        String s = Base64Utils.encodeToString(pic.getBytes());
        System.out.println("s:"+s);

        /* *
         *2.解码成字节数组
         */
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] bytes = decoder.decode(s);
        System.out.println("by:"+bytes);

        /*
         * 3.字节流转文件
         */
        String fileName = pic.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String caselsh = fileName.substring(0,fileName.lastIndexOf("."));
        //获取jar包所在目录
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
        String dirPath = jarF.getParentFile().toString()+"/upload/";
        System.out.println(dirPath);
        File fileMkdir = new File(dirPath);

//        String d = System.getProperty("user.dir");
//        File fileMkdir = new File(d+"\\src\\main\\resources\\public\\img");
//        File fileMkdir = new File("http://192.168.1.119:9002/img");
        if (!fileMkdir.exists()){
            fileMkdir.mkdir();
        }
        Date dd=new Date();
        SimpleDateFormat sim=new SimpleDateFormat("yyyyMMdd");
        String time=sim.format(dd);
        String pathName = fileMkdir.getPath() + "\\" + caselsh+time+"."+suffix;
        System.out.println("path"+pathName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(pathName);
            fos.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        HashMap<Integer,String> need = new HashMap<>();
        need.put(0,"upload/"+ caselsh+time+"."+suffix);
        return need;
    }

打成jar包后运行,则会在jar所在目录下自动生成upload文件存储上传的图片

为防止图片重名,按照日期和原名称更改:
文件名:
String fileName = pic.getOriginalFilename();
文件扩展名:
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
文件扩展前名字:
String caselsh = fileName.substring(0,fileName.lastIndexOf("."));
日期:
Date dd=new Date();
SimpleDateFormat sim=new SimpleDateFormat(“yyyyMMdd”);
String time=sim.format(dd);
更改后的文件路径 :
String pathName = fileMkdir.getPath() + “\” + caselsh+time+"."+suffix;

路径应该是动态的,随着jar包的路径变动的,为了实现这两点就需要做个视图解析器

package com.phoneback.config;


import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.io.File;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //获取jar包所在目录
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
        String dirPath = jarF.getParentFile().toString()+"/upload/";

        registry.addResourceHandler("/upload/**").addResourceLocations("file:" + dirPath);
    }
}

在这里插入图片描述

保存进数据库

在前端用upload的change函数,info.file.responce获取返回值,我的返回值是状态以及文件相对路径

 onChange: info => {
        if (info.file.status === 'done') {
            pic = info.file.response['0'];
            console.log(pic)
        }

    }

pic获取的是/upload/文件名.png
然后按照自己的需求调用接口传参存进数据库就可以读取啦


版权声明:本文为qq_42571665原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。