@RequestMapping(value = "/uploadPic.action")
@ResponseBody
public Response uploadPic(@RequestParam("picture") MultipartFile picture , HttpServletRequest request) {
Response response = new Response();
//获取文件在服务器的储存位置
String path = "D:/img";
File filePath = new File(path);
System.out.println("文件的保存路径:" + path);
if (!filePath.exists() && !filePath.isDirectory()) {
System.out.println("目录不存在,创建目录:" + filePath);
filePath.mkdir();
}
//获取原始文件名称(包含格式)
String originalFileName = picture.getOriginalFilename();
System.out.println("原始文件名称:" + originalFileName);
//获取文件类型,以最后一个.
为标识
String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
System.out.println("文件类型:" + type);
//获取文件名称(不包含格式)
String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));
//设置文件新名称: 当前时间+文件名称(不包含格式)
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String date = sdf.format(d);
String fileName = date + name + "." + type;
System.out.println("新文件名称:" + fileName);
//项目url,这里可以使用常量或者去数据字典获取相应的url前缀;
String fileUrl="http://localhost:8080";
//文件获取路径
fileUrl = fileUrl + request.getContextPath() + "/img/" + fileName;
//在指定路径下创建一个文件
File targetFile = new File(path, fileName);
//将文件保存到服务器指定位置
try {
picture.transferTo(targetFile);
System.out.println("上传成功");
//将文件在服务器的存储路径返回
response.setResult(fileUrl);
} catch (IOException e) {
e.printStackTrace();
response.setResult("上传失败");
}
return response;
}
后台