标签:
<body>
<h3>文件上传</h3>
<form action="/testAnnotationMVC_fileUpload/file/fileUpload2.jspx"
method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上 传" />
</form>
<h5>上传结果:</h5>
<img alt="暂无图片" src="${fileUrl}" />
</body> |
@Controller
@RequestMapping("/file")
public class fileUploadController {
@RequestMapping("/toFile")
//跳转到文件上传的JSP页面
public String toFileUpload() {
return "fileUpload";
}
@RequestMapping("/fileUpload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file,
HttpServletRequest request, ModelMap model) {
//获得原始文件名
String fileName = file.getOriginalFilename();
System.out.println("fileName:"+ fileName);
//新文件名
String newFileName = UUID.randomUUID()+fileName;
//上传到什么地方
String path = "d:/upload/";
File f = new File(path);
if(!f.exists())f.mkdirs();
if(!file.isEmpty()){
try {
FileOutputStream fos = new FileOutputStream(path+newFileName);
InputStream in = file.getInputStream();
int b = 0;
while((b=in.read())!=-1){
fos.write(b);
}
fos.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("imgurl:"+ path+newFileName);
//保存文件地址,用于JSP页面回显
model.addAttribute("fileUrl", path+newFileName);
return "fileUpload";
} } |
@RequestMapping("/fileUpload2")
public String fileUpload2(HttpServletRequest request,HttpServletResponse response) throws Exception{
CommonsMultipartResolver cmr = new CommonsMultipartResolver(request.getServletContext());
if(cmr.isMultipart(request)){
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest)(request);
Iterator<String> files = mRequest.getFileNames();
while(files.hasNext()){
MultipartFile mFile = mRequest.getFile(files.next());
if(mFile != null){
String fileName = UUID.randomUUID()+mFile.getOriginalFilename();
String path = "d:/upload/"+fileName;
File localFile = new File(path);
mFile.transferTo(localFile);
request.setAttribute("fileUrl", path);
}
}
}
return "fileUpload";
} |
标签:
原文地址:http://www.cnblogs.com/gtaxmjld/p/4427287.html