JSP代码部分:
<body>
<div data-role="content">
<form action="/file/updates" method="post" enctype="multipart/form-data">
<input type="file" class="input" name="file" multiple="multiple">
<div class="imgzip"></div>
<input type="submit" name="sub" value="提交" class="1">
</form>
</div>
</body>
js:代码部分
$("#upload").click(function () {
var formData = new FormData($('#uploadForm')[0]);
$.ajax({
type: 'post',
url: "../file/updates",
data: formData,
cache: false,
processData: false,
contentType: false,
}).success(function (data) {
alert(data);
}).error(function () {
alert("上传失败");
});
});
java代码部分:
@Controller
@RequestMapping("/file")
public class FileUploadController {
private static final Logger logger = LoggerFactory
.getLogger(FileUploadController.class);
/*
* 单个文件上传
*/
@RequestMapping(value = "/update", method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file,
HttpServletRequest request) throws Exception {
// 定义文件保存的本地路径
String localPath = "E:\\File\\";
// 定义 文件名
String filename = null;
// 获取文件名
String fileName = file.getContentType();
System.out.println("文件类型" + fileName);
// 生成uuid作为文件名称
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// 获得文件后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("/") + 1);
// 判断图片格式
// 得到 文件名
filename = uuid + "." + suffixName;
System.out.println(filename);
File filepath = new File(localPath);
// 判断上传文件的保存目录是否存在
if (!filepath.exists()) {
System.out.println(localPath + "目录不存在,需要创建");
// 创建目录
filepath.mkdir();
}
file.transferTo(new File(localPath + File.separator + filename));
return "/yes";
}
/*
* 多图片上传
*/
@RequestMapping(value = "/updates", method = RequestMethod.POST)
@ResponseBody
public String uploads(@RequestParam("file") MultipartFile[] file,
HttpServletRequest request) throws Exception {
String Prompt=null;
//判断上传的文件是否为空
if(file[0].getContentType().equals("application/octet-stream")){
Prompt="请添加文件!";
return Prompt ;
}
int imgnum=5;
Date day = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd\\");
String datepath = df.format(day);
// 定义文件保存的本地路径
String localPath = "E:\\File\\" + datepath;
File newfilepath = new File("E:\\File\\");
// 判断一级目录是否存在
if(!newfilepath.exists()){
System.out.println("E:\\File\\" + "目录不存在,需要创建");
// 创建目录
newfilepath.mkdir();
}
System.out.println("localPath:" + localPath);
File filepath = new File(localPath);
// 判断上传文件的保存目录是否存在
if (!filepath.exists()) {
System.out.println(localPath + "目录不存在,需要创建");
// 创建目录
filepath.mkdir();
}
// 定义 文件名
String filename = null;
for (int i = 0; i < file.length; i++) {
// 获取文件类型
filename = file[i].getContentType();
System.out.println("文件类型" + filename);
// 生成uuid作为文件名称
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// 获得文件后缀名
String suffixName = filename.substring(filename
.lastIndexOf("/") + 1);
// 判断图片格式
// 得到 文件名
filename = uuid + "." + suffixName;
file[i].transferTo(new File(localPath + File.separator
+ filename));
}
Prompt="上传成功 ";
return Prompt;
}
}