交互

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

@PostMapping("{id}")

public R pushinfo(@PathVariable Integer id , @RequestParam ("files") List 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 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);

long l = System.currentTimeMillis();

String s = Long.toString(l);

pushInfo.setPushinfoid(s);//根据当前时间生成唯一一个发布的动态的id

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;

}

}

文章来源

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: