SpringBoot图片的上传

实现一个选择图片上传并进行回显的功能

  1. 前端页面(部分代码)
<img id="blogCoverImage" src="/admin/dist/img/img-upload.png" style="height: 64px;width: 64px;">
<button class="btn btn-info" style="margin-bottom: 5px;" id="uploadCoverImage">
	<i class="fa fa-picture-o"></i>&nbsp;上传封面
</button>
  1. 发送ajax请求
$(function () {
new AjaxUpload('#uploadCoverImage', {
        action: '/admin/upload/file',
        name: 'file',
        autoSubmit: true,
        responseType: "json",
        onSubmit: function (file, extension) {
            if (!(extension && /^(jpg|jpeg|png|gif)$/.test(extension.toLowerCase()))) {
                alert('只支持jpg、png、gif格式的文件!');
                return false;
            }
        },
        onComplete: function (file, r) {
            if (r != null && r.resultCode == 200) {
                $("#blogCoverImage").attr("src", r.data);
                $("#blogCoverImage").attr("style", "width: 128px;height: 128px;display:block;");
                return false;
            } else {
                alert("error");
            }
        }
    });
});
  1. 后端
@Controller
@RequestMapping("/admin")
public class UploadController {

    @PostMapping({"/upload/file"})
    @ResponseBody
    public Result upload(HttpServletRequest httpServletRequest, @RequestParam("file") MultipartFile file) throws URISyntaxException {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();
        File fileDirectory = new File("D:/upload");
        //创建文件
        File destFile = new File("D:/upload" + newFileName);
        try {
            if (!fileDirectory.exists()) {
                if (!fileDirectory.mkdir()) {
                    throw new IOException("文件夹创建失败,路径为:" + fileDirectory);
                }
            }
            file.transferTo(destFile);
            Result resultSuccess = ResultGenerator.genSuccessResult();
            resultSuccess.setData(MyBlogUtils.getHost(new URI(httpServletRequest.getRequestURL() + "")) + "/upload/" + newFileName);
            return resultSuccess;
        } catch (IOException e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("文件上传失败");
        }
    }

}

返回给前端的数据封装为Result对象

  1. 配置配置资源映射路径
@Configuration
public class MyBlogWebMvcConfigurer implements WebMvcConfigurer {
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    //addResourceLocations指的是文件放置的目录,addResoureHandler指的是对外暴露的访问路径("file:"是规定写法)
        registry.addResourceHandler("/upload/**").addResourceLocations("file:" + "E:/upload");
    }
}
  1. 前端接受到相应后通过相应代码进行回显
$("#blogCoverImage").attr("src", r.data);
$("#blogCoverImage").attr("style", "width: 128px;height: 128px;display:block;");

在这里插入图片描述

发布了76 篇原创文章 · 获赞 0 · 访问量 2003

猜你喜欢

转载自blog.csdn.net/weixin_43907800/article/details/104180923
今日推荐