0
点赞
收藏
分享

微信扫一扫

NXB发布动态功能

陆佃 2022-01-31 阅读 44

交互

post方式,一个路径变量id,其他的所有属性都不传表单,而是单独传值(不是路径变量)
全部利用@RequestParam传值

@PostMapping("{id}")
public R pushinfo(@PathVariable Integer id , @RequestParam ("files") List<MultipartFile> files,
                   @RequestParam("info") String infomation,
                  @RequestParam("tag") String tag,
                  @RequestParam("location") String location){

文件单独存储

    String filePath = "D:\\NXBfiles\\";//文件存储路径

    for(MultipartFile f : files) {//对每个文件进行存储


        String ss = f.getOriginalFilename().split("\\.")[1];//拿到文件格式,如png jpg

        pushInfo.setFileName(System.currentTimeMillis()+"." + ss);//计数器+1
        //当前时间戳 + 后缀   保证不会冲突
        File dest = new File(filePath,pushInfo.getFileName());//最终存储的文件

        try {
            f.transferTo(dest);//把读到内存中的文件转移到dest去
        } catch (IOException e) {
            e.printStackTrace();
             r.setFlag(false);
    //不用setMsg,因为拦截器会处理
            return r;//出异常直接返回
        }
    }

文件名设计

当前时间+后缀,千万不能在实体类中定义static int count,因此每次运行的count都是从0开始了

数据库设计

id不能为空,并且ID不能为主键,否则同一个ID只能存储一次

时间自动创建

postman测试

数据库内容

控制层源码

@RestController
@RequestMapping("pushinfo")
public class PushInfoController {
    @Autowired
    IMPPushInfoService impPushInfoService;

    //发布内容
    @PostMapping("{id}")
    public R pushinfo(@PathVariable Integer id , @RequestParam ("files") List<MultipartFile> files,
                       @RequestParam("info") String infomation,
                      @RequestParam("tag") String tag,
                      @RequestParam("location") String location){
        //千万不能给PushInfo加@RequestBody
//从路径获取id,根据主键id存储;获取多条上传的文件list;获取PushInfo对象
        PushInfo pushInfo = new PushInfo();
        pushInfo.setId(id);
        pushInfo.setInfomation(infomation);
        pushInfo.setTag(tag);
        pushInfo.setLocation(location);
        R r = new R();
//        if(files.isEmpty()) {
//            r.setMsg("未上传图片");
//        }

        String filePath = "D:\\NXBfiles\\";//文件存储路径

        for(MultipartFile f : files) {//对每个文件进行存储


            String ss = f.getOriginalFilename().split("\\.")[1];//拿到文件格式,如png jpg

            pushInfo.setFileName(System.currentTimeMillis()+"." + ss);//计数器+1
            //当前时间戳 + 后缀   保证不会冲突
            File dest = new File(filePath,pushInfo.getFileName());//最终存储的文件

            try {
                f.transferTo(dest);//把读到内存中的文件转移到dest去
            } catch (IOException e) {
                e.printStackTrace();
                 r.setFlag(false);
        //不用setMsg,因为拦截器会处理
                return r;//出异常直接返回
            }
        }

        r.setFlag(impPushInfoService.save(pushInfo));

        if(r.getFlag()==true) {
            r.setMsg("已发布");
            r.setData(pushInfo);//包括了从前端传来的位置,标签,信息内容
        }else{
            r.setMsg("发布失败");
        }
/*
* 这里设置的fileName属性是一个唯一的,相对的路径
* 所以在取的时候,也需要相对取
* */
return r;

    }




}
举报

相关推荐

0 条评论