The Springboot avatar image is uploaded using formdata, and the URL is displayed to return the image, and the avatar can be modified

1. The front end sends the avatar image resource to formdata in the form of Ajax request to the back end

1. For the author who wrote an afternoon bug, decided to share all the bugs encountered here to avoid everyone from stepping on the pit like me. First let everyone see the page effect, click on the picture to select, and then click upload Upload the image, and you will debug the
Insert picture description here
html part yourself in CSS style :

<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 part:
There are some pitfalls of using formdata:

  1. contentType: false is to prevent jQuery from handling contentType, don't add contentType to multipart / form-data, because the browser will add it for you, so don't add it on meta. Otherwise, boundary will appear. . . , The problem that the border cannot be found.
  2. processData: false is to prevent jQuery from processing the data into a string because you are uploading an image
$("#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. The back-end Controller section

1.controller, write the picture to the local and send it back to the front end

	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. Create MyWebMvcConfigurer and configure the resource mapping path, which is used by springboot2.x

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

3. Then you can see that the modification is successful
Insert picture description here

Published 25 original articles · praised 4 · visits 1516

Guess you like

Origin blog.csdn.net/weixin_39025362/article/details/105512580