package com.zhiyou100.kfs.controller;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.zhiyou100.kfs.bean.User;
@Controller
@RequestMapping("user")
public class UserController {
@RequestMapping("upload")
public String upload(ModelAndView mv,User user,MultipartFile[] myfile,HttpServletRequest request) {
mv.setViewName("tes");
//1.通过request获取文件真实上传路径
String pathname=request.getServletContext().getRealPath("/photo");
System.out.println(pathname);
//2.通过真实路径创建文件
File file=new File(pathname);
if(!file.exists()) {//判断是否存在,若不存在则新建
file.mkdirs();
}
for(MultipartFile f:myfile) {
if(f.getSize()>0) {
//3.通过MultipartFile对象获取文件名
String fileName=f.getOriginalFilename();
user.setPhone(fileName);
System.out.println(user);
File targetFile=new File(pathname+"/"+fileName);
try {
//4.保存文件到目标目录
f.transferTo(targetFile);
//4.通过FileUtils把MultipartFile的文件复制到目标文件
// FileUtils.writeByteArrayToFile(targetFile, f.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "index:"+user.getUserId();
}
}