Upload now generally use the framework to upload, almost the most basic upload forget, here to write a review about the normal upload
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>file文件操作测试</title>
</head>
<body>
<input type="file" id="file1" name="file1" style="display:none">
<button type="button" id="gofile">上传文件</button>
</body>
<script src="https://libs.baidu.com/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
//提交后台
$("#gofile").on("click", function () {
$("#file1").click();
});
$("#file1").on("change", function () {
var formData = new FormData();
formData.append("files", $("#file1")[0].files[0]);
$.ajax({
type:'POST',
url:"/test/main/uploadfile",
data:formData,
contentType:false,
processData:false,
// dataType:"json",
mimeType:"multipart/form-data",
success:function(data){
if(data=="true"){
alert("保存成功!");
}else{
alert("保存失败!");
}
}
});
});
</script>
</html>
/**
* 上传
* @return
*/
@RequestMapping(value="/uploadfile",method = RequestMethod.POST)
@ResponseBody
public String uploadfile(@RequestParam("files") MultipartFile files) throws IOException{
return setFile(files)==true?"true":"false";
}
public boolean setFile(MultipartFile multipartFile) throws IOException {
boolean filetype=false;
try {
String packingId="9527";
String name = "";
if (multipartFile != null) {
name = multipartFile.getOriginalFilename();// 直接返回文件的名字
String subffix = name.substring(name.lastIndexOf(".") + 1, name.length());// 我这里取得文件后缀
String name1=name.substring(0,name.lastIndexOf ( ".")); // save the name of the original file to another location
String fileName = packingId + getDateFormat (new Date (), "YYYYMMDDHHMMSS"); // save the file came in, I gave him rename
String filepath = "D: \\ File \\" + packingId;
File File = new new File (filepath );
IF) {// create a directory does not exist on (File.Exists (!)
file.mkdirs ();
}
// this method can be added
multipartFile.transferTo (new File (file + " \\" + fileName + + subffix)) "." ; // save file
}
filetype = to true;
} the catch (Exception E) {
System.out.println (E);
filetype = to false;
return filetype;
}
return filetype;
}
/ **
* date format
*
* @param dATE
* @param format type
* @return
* /
public static String getDateFormat(Date date, String formatStr) {
if (!StringUtils.isEmpty(formatStr)) {
return new SimpleDateFormat(formatStr).format(date);
}
return null;
}
Get it - of course, this is based on the environmental situation at the download
<! - this can add upload ->
<bean the above mentioned id = "the MultipartResolver" class = "org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<!-- 实现上传需要的jar -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>