用户头像上传(自用)

1、controller控制类

@Api(value = "用户信息接口", tags = {"用户信息接口相关接口"})
@RestController
@RequestMapping("userInfo")
public class CenterUserController extends BaseController {

    @Autowired
    private CenterUserService centerUserService;

    @Autowired
    private FileUpload fileUpload;

    @ApiOperation(value = "用户头像修改", notes = "用户头像修改")
    @PostMapping("uploadFace")
    public JSONResult uploadFace(
            @ApiParam(name = "userId", value = "用户id", required = true)
            @RequestParam String userId,
            @ApiParam(name = "file", value = "用户头像", required = true)
            MultipartFile file,
            HttpServletRequest request,
            HttpServletResponse response){
        //定义头像保存的地址
//        String fileSpace = IMAGE_USER_FACE_LOCATION;
        String fileSpace = fileUpload.getImageUserFaceLocation();
        //在路径上为每一个用户增加一个userId文件夹 /{userId},用于区分不同用户上传
        String uploadPathPrefix = File.separator + userId;

        FileOutputStream fileOutputStream = null;
        try {
            //开始文件上传
            if (file != null){
                //获得文件的上传名称
                String fileName = file.getOriginalFilename();
                if (StringUtils.isNotBlank(fileName)){
                    //文件重命名
                    String[] fileNameArr = fileName.split("\\.");
                    //获取文件的后缀名
                    String suffix = fileNameArr[fileNameArr.length - 1];

                    //防止黑客攻击,上传 .sh .php
                    if (!suffix.equalsIgnoreCase("png") &&
                            !suffix.equalsIgnoreCase("jpg") &&
                            !suffix.equalsIgnoreCase("jpeg")){
                        return JSONResult.errorMsg("图片格式不正确!仅支持.png .jpg .jpeg");
                    }

                    //文件名称重组 覆盖式上传。 如果要使用增量式:额外拼接当前时间
                    //face-{userId}.png
                    String newFileName = "face-" + userId+ "." + suffix;
                    //上传的头像最终保存的位置
                    String finalFacePath = fileSpace + uploadPathPrefix + File.separator + newFileName;

                    //用于提供web服务的访问地址
                    uploadPathPrefix += ("/" + newFileName);

                    File outFile = new File(finalFacePath);
                    //如果父级文件夹不存在,则创建
                    if (outFile.getParentFile() != null){
                        //创建文件夹
                        outFile.getParentFile().mkdirs();
                    }

                    //文件输出保存到目录
                    fileOutputStream = new FileOutputStream(outFile);
                    InputStream inputStream = file.getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (fileOutputStream != null){
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //获取服务端图片地址
        String imageServerUrl = fileUpload.getImageServerUrl();
        //web服务端最终访问地址
        //由于浏览器可能存在缓存的情况,所有在这里,我们可以加上一个时间戳来保证更新的图片及时刷新
        String finalServerFaceUrl = imageServerUrl + uploadPathPrefix
                + "?t=" + DateUtil.getCurrentDateString(DateUtil.DATE_PATTERN);

        //更新用户头像到数据库
        Users userResult = centerUserService.updateUserFace(userId, finalServerFaceUrl);

        //更新cookie
        userResult = setNullProperty(userResult);
        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(userResult),true);

        //TODO 后续要改,增加令牌token,会整合进redis,分布式会话

        return JSONResult.ok();
    }
}

2、图像上传地址类:FileUpload.java

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "file") //属性前缀
@PropertySource("classpath:file-upload-dev.properties") //配置文件地址
public class FileUpload {
    private String imageUserFaceLocation;

    private String imageServerUrl;

    public String getImageUserFaceLocation() {
        return imageUserFaceLocation;
    }

    public void setImageUserFaceLocation(String imageUserFaceLocation) {
        this.imageUserFaceLocation = imageUserFaceLocation;
    }

    public String getImageServerUrl() {
        return imageServerUrl;
    }

    public void setImageServerUrl(String imageServerUrl) {
        this.imageServerUrl = imageServerUrl;
    }
}

3、将配置文件中的具体地址,通过注释传入FileUpload.java定义的属性中。故下面是具体地址配置类

#开发环境
file.imageUserFaceLocation = D:\\src\\photo
file.imageServerUrl = http://localhost:8088

文件位置

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值