package com.lanou.handler;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.lanou.service.ISpImgService;
@Controller
// 定义了命名空间
@RequestMapping("/insertImg")
public class SPImgController {
public static Logger log = Logger.getLogger(SPImgController.class);
@Resource(name = "spimgservice")
public ISpImgService service;
// 实现多图片上传
@RequestMapping("/insert")
public ModelAndView insertAll(@RequestParam("file")MultipartFile[] file, HttpSession session,String str) throws IOException{
int a=0;
Map<String, Object> map=new HashMap<>();
for (MultipartFile multipartFile : file) {
a=a+1;
log.info(multipartFile.getOriginalFilename());
String realPath=session.getServletContext().getRealPath("");//文件的绝对路径
String fileFileName=multipartFile.getOriginalFilename();//文件名
log.info("文件名:"+fileFileName);
String[] temp = fileFileName.split("\\.");// 转译字符.
temp[0] = System.currentTimeMillis() + session.getId();
log.info("上传文件的绝对路径 :"+realPath);
String finalString = "";//图片最终名字
for (int i = 0; i < temp.length; i++) {
if (i == 0) {
finalString = temp[i]+".";
} else if (i == temp.length - 1) {
finalString = finalString+temp[i];
}else{
finalString=finalString+temp[i]+".";
}
}
log.info(finalString);
//注意ip写成自己的
String patternPath = "http://192.168.20.171:8080/sports/html/img/"+""+a+""+finalString;
if(!multipartFile.isEmpty()){
FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),new File(realPath+"/html/img/"+""+a+""+ finalString));
log.info("上传成功了"+patternPath);
}
log.info(patternPath);
map.put("spimg"+a+"", patternPath);
}
map.put("sp_d", str);
service.insertAll(map);
return new ModelAndView("spimg");
}
}