SpringBoot实现文件上传

代码实现:

controller层

@ApiOperation(value = "上传头像接口", notes = "上传头像接口", httpMethod = "POST")
    @PostMapping("/uploadFace")
    public JSONResult uploadFace(@RequestParam("userId") String userId,
                                 MultipartFile file,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {
        if (file != null) {
            //获取文件的名称
            String originalFilename = file.getOriginalFilename();
            FileOutputStream fileOutputStream = null;
            if (StringUtils.isNotBlank(originalFilename)) {
                //分割文件名
                String[] split = originalFilename.split("\\.");
                //获取文件后缀名
                String suffix = split[split.length - 1];
                if(!suffix.equals("jpg") && !suffix.equals("png") && !suffix.equals("jpeg")){
                    return JSONResult.errorMap("请选择正确的图片格式(jpg,png,jpeg)!");
                }
                //重新定义文件名
                String newfileName = "face-" + userId + "." + suffix;
                //文件最终保存地址
                String finalFilePath = fileUploadResource.getImageUserFaceLocation() + "\\" +userId+"\\"+ newfileName;
                File file1 = new File(finalFilePath);
                if (file1.getParentFile() != null) {
                    //创建文件夹
                    file1.getParentFile().mkdirs();
                }

                try {
                    fileOutputStream = new FileOutputStream(file1);
                    InputStream inputStream = file.getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (fileOutputStream != null) {
                        try {
                            fileOutputStream.flush();
                            fileOutputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                //图片访问地址
                String finalUserFaceUrl = fileUploadResource.getImageUserFaceServcerUrl() + userId + "\\" + newfileName+"?t="+ DateUtil.getCurrentDateString(DateUtil.DATE_PATTERN);
                Users users = centerService.updateUserFace(userId, finalUserFaceUrl);
                CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(setUserNullProperty(users)), true);
 
            }
        }


        return JSONResult.ok();

    }

配置文件,file-upload-dev.properties:

//头像保存地址
file.imageUserFaceLocation=F:\\myproject\\foodie-shop\\image\\face
//头像访问地址
file.imageUserFaceServcerUrl=http://localhost:8088/face/

配置文件与类文件进行映射,FileUploadResource:

package com.ljt.resource;

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

import javax.annotation.Resources;

@Component
@ConfigurationProperties(prefix = "file")
@PropertySource("classpath:file-upload-dev.properties")
public class FileUploadResource {
    private String imageUserFaceLocation;
    private String imageUserFaceServcerUrl;

    public String getImageUserFaceServcerUrl() {
        return imageUserFaceServcerUrl;
    }

    public void setImageUserFaceServcerUrl(String imageUserFaceServcerUrl) {
        this.imageUserFaceServcerUrl = imageUserFaceServcerUrl;
    }

    public String getImageUserFaceLocation() {
        return imageUserFaceLocation;
    }

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

自定义异常,防止上传文件太大,抛出异常,前端无法识别,CustomExceptionHandler:

package com.ljt.exception;

import com.ljt.utils.JSONResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

@RestControllerAdvice
public class CustomExceptionHandler {


    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public JSONResult handlerMaxUploadFile(MaxUploadSizeExceededException exceededException){
        return JSONResult.errorMsg("上传图片太大,请选择小于500kb的图片!");
    }
}

测试结果:

SpringBoot实现文件上传_第1张图片

你可能感兴趣的:(1024程序员节,spring,boot,spring,java)