Springboot头像图片使用formdata上传,回传URL显示图片,可做头像修改

1.前端通过Ajax请求将头像图片资源发送formdata的形式请求后端

1、对于写了一个下午bug的笔者,决定把在此遇到的bug都分享给大家,避免大家也像我一样踩坑,首先让大家看看页面效果,点击图片选择,然后点击上传即可上传图片,css样式大家就自己调试了
在这里插入图片描述
html部分:

<label class="control-label file">
    <div>
        <img id="userUrl" style="border-radius: 100px;" src="${user.userUrl}">
    </div>
    <input type="file" id="photo">
    <input type="hidden" id="userId" value="${user.userId}">
</label>
<p style="margin-left: 20px;">点击头像选择图片,再点击上传</p>
<input id="changeBtn" class="btn btn-info" value="上传">

js部分:
使用formdata有些很坑的点:

  1. contentType:false是为了不让jQuery处理contentType,不要自己添加contentType为multipart/form-data,因为浏览器会自己帮你加上去,所以也不要再meta上添加。否则会出现boundary。。。,边界找不到的问题。
  2. processData:false是为了不让jQuery将数据处理成字符串,因为你要上传的是图片
$("#changeBtn").click(function () {
        var formData = new FormData();
        formData.append("photo",$('input#photo')[0].files[0]);
        formData.append("userId",$("#userId").val());//业务需求,需要把图片和用户关联起来
        $.ajax({
            url: "自己上传文件的url",
            type: 'POST',
            contentType: false,
            processData: false,
            data: formData,
            success: function (data) {
                $.alert({
                    title: data.code,
                    content: data.msg,
                });
                $("#userUrl").attr("src", data.userUrl); //使用jquery修改图片的src
            },
            error: function (data) {
                $.alert({
                    title: 'Error',
                    content: '修改头像失败,请稍后重试!',
                });
            }
        });
    });

3.后端Controller部分

1.controller,将图片写入到本地,并回传给前端

	private final String writePath = "F:\\images";   //写入本地保存的绝对路径

    private final String savePath = "/images/";   //写入数据库中的路径

	@RequestMapping(value = "/changePhoto")
    @ResponseBody
    public Map<String,String> changePhoto(@RequestParam MultipartFile photo, @RequestParam Long userId){
        Map<String,String> data = new HashMap<>();
        if (photo.isEmpty()){
            data.put("code","error");
            data.put("msg","上传图片为空!");
            return data;
        }
        //获取MultipartFile文件的后缀
        String suffix = photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf(".") + 1);
        //限制只能上传三种图片格式,不要使用==,因为他是比较基本数据类型的,String是对象
        if (suffix.equalsIgnoreCase("jpg") ||
                suffix.equalsIgnoreCase("jpeg") ||
                suffix.equalsIgnoreCase("png")){
            OutputStream os = null;
            InputStream inputStream = null;
            String fileName = (userId + "") + System.currentTimeMillis() + ".jpg";
            String userUrl = savePath+fileName;
            try {
                inputStream = photo.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                byte[] bs = new byte[1024];
                int len;
                // 输出的文件流保存到本地文件
                File tempFile = new File(writePath);
                if (!tempFile.exists()) {
                    tempFile.mkdirs();
                }
                os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
                // 开始读取
                while ((len = inputStream.read(bs)) != -1) {
                    os.write(bs, 0, len);
                }
                os.flush();
                userService.updateUserUserUrl(userId,userUrl);
                System.out.println(userUrl);
                data.put("userUrl",userUrl);
                data.put("code","success");
                data.put("msg","修改头像成功");
                return data;
            } catch (IOException e) {
                e.printStackTrace();
                data.put("code","error");
                data.put("msg","修改头像失败,请稍后重试!");
                return data;
            } catch (Exception e) {
                e.printStackTrace();
                data.put("code","error");
                data.put("msg","修改头像失败,请稍后重试!");
                return data;
            } finally {
                // 完毕,关闭所有链接
                try {
                    os.close();
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else {
            data.put("code","error");
            data.put("msg","上传头像格式需要为jpg、jpeg、png!");
            return data;
        }
    }

2.创建MyWebMvcConfigurer,配置资源映射路径,这是springboot2.x使用的

@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**").addResourceLocations("file:F:/images/");
    }
}

3.接着就可以看到修改成功了
在这里插入图片描述

发布了25 篇原创文章 · 获赞 4 · 访问量 1516

猜你喜欢

转载自blog.csdn.net/weixin_39025362/article/details/105512580
今日推荐