欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java文件上传

程序员文章站 2024-02-19 11:10:16
...

以添加轮播图为例:

	/**
     * 添加轮播信息
     *
     * @param request
     * @param file
     * @param carousel
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/addCarousel")
    public RecycleResult addCarousel(HttpServletRequest request, MultipartFile file, Carousel carousel) throws IOException {
        if (file == null || StringUtils.isBlank(file.getOriginalFilename())){
            RecycleResult.build(500, "文件不能为空");
        }

        String rootPath = ResourceUtils.getURL("").getPath() + "static/upload/";
        File rootFile = new File(rootPath);
        if (!rootFile.exists()) {
            rootFile.mkdirs();
        }
        String realPath = new Date().getTime() + file.getOriginalFilename();
        //存储文件
        File storeFile = new File(rootPath + realPath);

        file.transferTo(storeFile);

        //写入数据库
        carousel.setPhotoPath(realPath);

        if (carousel != null){
            cmsService.addCarousel(carousel);
        }
        return RecycleResult.ok();
    }

LayuiReplay类(其中get、set方法省略)

public class LayuiReplay <T> {
    private int code;
    private String msg;
    private int count;
    private List<T> data;
 
    public LayuiReplay(int code, String msg, int count, List<T> data) {
        this.code = code;
        this.msg = msg;
        this.count = count;
        this.data = data;
    }
 
    public String toJson() {
        Gson gson = new Gson();
        String json = gson.toJson(this);
        return json;
    }
 
    public static <T> String toJson(int count, List<T> data) {
        LayuiReplay<T> replay = new LayuiReplay<>(ReplyCode.OK.getCode(), ReplyCode.OK.getMessage(), count, data);
        return replay.toJson();
    }
}