SpringMVC接收文件

场景

前端或APP端设置头像或发表评论等功能,需要服务端接收图片,然后保存到nginx代理路径,返回前端图片的URL。

form表单提交

前段使用form表单提交时,服务端使用org.springframework.web.multipart.MultipartFile接收。

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    @Value(value = "${image.path:./img}")
    private String imagePath;

    @Value(value = "${image.host:http://localhost}")
    private String imageHost;

    @RequestMapping(value = "/upload/file", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> saveFile(@RequestParam(value = "img") MultipartFile file) {
        StringBuffer fileName = new StringBuffer();
        fileName.append(UUID.randomUUID().toString().replaceAll("-", ""));
        String type = file.getContentType();
        if ("image/png".equals(type)) {
            fileName.append(".png");
        } else if ("image/jpeg".equals(type)) {
            fileName.append(".jpeg");
        } else if ("image/gif".equals(type)) {
            fileName.append(".gif");
        } else {
            return new Result.Builder<String>()
                    .code(-1)
                    .msg("请选择.png.jpg格式的图片")
                    .build();
        }
        if (file.getSize() > 1024000L) {
            return new Result.Builder<String>()
                    .code(-1)
                    .msg("图片超过1Mb")
                    .build();
        }
        try {
            file.transferTo(new File(imagePath, fileName.toString()));
            return new Result.Builder<String>()
                    .code(0)
                    .msg("成功")
                    .data(imageHost + fileName.toString())
                    .build();
        } catch (IOException e) {
            e.printStackTrace();
            return new Result.Builder<String>()
                    .code(-1)
                    .msg("保存失败")
                    .build();
        }
    }
}

application.yml配置

image:
  host: http://localhost/img/
  path: /data/www/img

图片文件用UUID重命名后保存到/data/www/img下,nginx将80访问代理到/data/www,这样,访问时的URL为路径➕文件名。

ajax提交Base64格式的图片

    @RequestMapping(value = "/upload/base64", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> saveBase64(@RequestParam(value = "img") String base64Str) {
        StringBuffer fileName = new StringBuffer();
        fileName.append(UUID.randomUUID().toString().replaceAll("-", ""));
        if (StringUtils.isBlank(base64Str)) {
            return new Result.Builder<String>()
                    .code(-1)
                    .msg("file不可缺省")
                    .build();
        } else if (base64Str.indexOf("data:image/png;") != -1) {
            base64Str = base64Str.replace("data:image/png;base64,", "");
            fileName.append(".png");
        } else if (base64Str.indexOf("data:image/jpeg;") != -1) {
            base64Str = base64Str.replace("data:image/jpeg;base64,", "");
            fileName.append(".jpeg");
        } else {
            return new Result.Builder<String>()
                    .code(-1)
                    .msg("请选择.png.jpg格式的图片")
                    .build();
        }
        File file = new File(imagePath, fileName.toString());
        byte[] fileBytes = Base64.getDecoder().decode(base64Str);
        try {
            FileUtils.writeByteArrayToFile(file, fileBytes);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result.Builder<String>()
                    .code(-1)
                    .msg("保存失败")
                    .build();
        }
        return new Result.Builder<String>()
                .code(0)
                .msg("成功")
                .data(imageHost + fileName.toString())
                .build();
    }

你可能感兴趣的:(备忘)