在Springboot使用form上传图片作为头像,之后通过ajax渲染img的src属性显示图片遇到的路径问题处理小技巧

2023-10-31

业务流程大概是这样的:在Springboot框架下,使用form提单提交用户注册信息,包括图片。图片被保存到服务器上,把图片保存的路径作为属性存入数据库。之后,显示用户信息的时候,通过Ajax获取用户信息,将图片的路径赋值给<Img>的src属性。

但是这里存在一个问题,就是图片的路径是绝对路径,如果给src的话,会产生跨域问题,显示不出来。

这里使用一个小技巧,在保存图片时,获取项目的真实路径

ResourceUtils.getURL("classpath:").getPath()

然后拼接,加“static/自定义路径”。这样就把图片保存到了项目的静态资源下边。然后把static/以后的路径截取下来保存到用户信息中,这个路径就是项目获取图片的相对路径

代码如下:

图片工具类:

@Slf4j
public class FileUtils {

    public static String saveUserImg(MultipartFile file) throws IOException {

        File outfile = null;
        try {
            BufferedOutputStream out = null;
            String filename = createRandomName() + "." + file.getOriginalFilename().split("[.]")[1];
            outfile = new File(createRandomPath(), filename);
            log.info(outfile.getName());
            out = new BufferedOutputStream(new FileOutputStream(outfile));
            System.out.println(file.getName());
            out.write(file.getBytes());
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //截取相对路径
        String[] strings = outfile.getCanonicalPath().split("static");
        return outfile.getCanonicalPath().split("static")[1];
//        return outfile.getPath();
    }

    /**
     * 返回文件保存路径,如果路径文件夹存在,则返回路径,如果不存在,则创建路径
     * @return
     */
    public static File createRandomPath() throws FileNotFoundException {

        File file  = new File(ResourceUtils.getURL("classpath:").getPath() + "/static/teacherFiles/Imges");
        if (!file.exists()){
            file.mkdirs();
        }
        return file;
    }

    /**
     * 生成随机文件名
     * @return
     */
    public static String createRandomName() {
        Long pre = new Date().getTime();
        Random random = new Random(new Date().getTime());
        Long suf = random.nextLong();
        String name = String.valueOf(pre) + String.valueOf(suf);
        return name;
    }

JS代码

<script type="text/javascript" >
        $(document).ready(function () {
            var userId = $("#hiddenUserID").valueOf().val()
            $.ajax({
                type: "GET",
                url: "/user/getuser?id=" + userId,
                dataType: "json",
                success: function (data) {
                    //省略
                    $("#updateTime").val(data.updateTime);
                    //设置图片路径
                    $("#userImg").attr("src", data.userImages);
                }
            })
        })
    </script>

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在Springboot使用form上传图片作为头像,之后通过ajax渲染img的src属性显示图片遇到的路径问题处理小技巧 的相关文章

随机推荐