package com.upload;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
@Controller
public class UploadContronller {
@RequestMapping("/toUpload.shtml")
public String toUpload(){
return "upload";
}
@RequestMapping(value="/upload.shtml")
public String upload(@RequestParam(value="file",required=false)CommonsMultipartFile file,
HttpServletRequest request,ModelMap model) throws Throwable{
// request.setCharacterEncoding("UTF-8");
if (request.getCharacterEncoding() == null) {
request.setCharacterEncoding("UTF-8");
}
// String type=file.getContentType();
//獲取存儲路徑
String path=request.getSession().getServletContext().getRealPath("upload");
//上傳文件名稱
String fileName=file.getOriginalFilename();
System.out.println(fileName);
//轉義拆分重命名文件
String[] strArr=fileName.split("\\.");
System.out.println(strArr[0]);
System.out.println(strArr[1]);
SimpleDateFormat sdf=new SimpleDateFormat("YYYYMMDDHHmmss");
String strName=sdf.format(new Date());
fileName=strName+"."+strArr[1];
System.out.println("------文件路徑:"+path);
//創建存儲目錄
File targetFile=new File(path,fileName.toString());
if(!targetFile.exists()){
targetFile.mkdirs();
}
//文件上傳
try {
file.transferTo(targetFile);
//將文件路徑轉發到頁面
model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "result";
}
}
try {
fileName = new String(fileName.getBytes(), "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}