81,091
社区成员
发帖
与我相关
我的任务
分享
你把代码贴出来,不要图片,我给你改,这么简单的逻辑都想不通的话,那你之前的代码是怎么写出来的
@RequestMapping(value = "/addNews", method = RequestMethod.POST)
private String fildUpload(News news ,@RequestParam(value="file",required=false) MultipartFile[] file,
HttpServletRequest request)throws Exception{
//定义序号
int count=1;
for (MultipartFile mf : file) {
if(!mf.isEmpty()){
// 使用UUID给图片重命名,并去掉四个“-”
String name = UUID.randomUUID().toString().replaceAll("-", "");
// 获取文件的扩展名
String ext = FilenameUtils.getExtension(mf
.getOriginalFilename());
// 设置图片上传路径
String url = request.getSession().getServletContext()
.getRealPath("/upload");
System.out.println(url);
// 以绝对路径保存重名命后的图片
mf.transferTo(new File(url + "/" + name + "." + ext));
// 把图片存储路径保存到数据库
String path="upload/" + name + "." + ext;
if(count==1){
news.setImg1(path);
}else if(count==2){
news.setImg2(path);
}else if(count==3){
news.setImg3(path);
}
}
count++;
}
newsService.addNews(news);
return "redirect:/newsList";
}
代码没有经过测试,大概就是这个逻辑代码没有经过测试,大概就是这个逻辑@RequestMapping(value = "/addNews", method = RequestMethod.POST) private String fildUpload(News news ,@RequestParam(value="file",required=false) MultipartFile[] file, HttpServletRequest request)throws Exception{ //定义序号 int count=1; for (MultipartFile mf : file) { if(!mf.isEmpty()){ // 使用UUID给图片重命名,并去掉四个“-” String name = UUID.randomUUID().toString().replaceAll("-", ""); // 获取文件的扩展名 String ext = FilenameUtils.getExtension(mf .getOriginalFilename()); // 设置图片上传路径 String url = request.getSession().getServletContext() .getRealPath("/upload"); System.out.println(url); // 以绝对路径保存重名命后的图片 mf.transferTo(new File(url + "/" + name + "." + ext)); // 把图片存储路径保存到数据库 String path="upload/" + name + "." + ext; if(count==1){ news.setImg1(path); }else if(count==2){ news.setImg2(path); }else if(count==3){ news.setImg3(path); } } count++; } newsService.addNews(news); return "redirect:/newsList"; }
你把代码贴出来,不要图片,我给你改,这么简单的逻辑都想不通的话,那你之前的代码是怎么写出来的
你这种写法每次循环都重新设置三个图片地址了,所以结果就是只能取到最后一个文件。可以在for循环设置一个序号,每次循环set一次。 if(count==1) news.setImg1...这样类推,如果个数较多要做成灵活的,那就要用反射了
你这种写法每次循环都重新设置三个图片地址了,所以结果就是只能取到最后一个文件。可以在for循环设置一个序号,每次循环set一次。 if(count==1) news.setImg1...这样类推,如果个数较多要做成灵活的,那就要用反射了