Java 上传文件:
<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="keyword1,keyword2,keyword3"></meta>
<meta name="description" content="this is my page"></meta>
<meta name="content-type" content="text/html; charset=UTF-8"></meta>
<title>图片上传</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/testUploadimg">
图片:
<input type="file" id="mf" name="file"/><br/>
<input type="submit" value="上传" />
<input type="submit" id="sub_btn" value="上传2" />
</form>
</body>
<script>
$(function () {
$("#sub_btn").click(function () {
var formData=new FormData();
formData.append("file",$("#mf")[0]);
$.ajax({
type:"post",
url:"testUploadimg",
dataType:"json",
data:formData,
cache: false,
processData: false,
contentType: false,
success:function (result) {
}
})
})
})
</script>
</html>
@Controller
public class UploadController {
@RequestMapping(value = "/gouploadimg", method = RequestMethod.GET)
public String goUploadImg() {
return "uploadimg";
}
@ResponseBody
@RequestMapping(value = "/testUploadimg", method = RequestMethod.POST)
public String uploadImg(@RequestPart("file") MultipartFile file) {
String contentType = file.getContentType();
String fileName = file.getOriginalFilename();
String filePath = "D:/img";
if (file.isEmpty()) {
return "文件为空!";
}
try {
uploadFile(file.getBytes(), filePath, fileName);
} catch (Exception e) {
}
return "上传成功";
}
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath +"/"+ fileName);
out.write(file);
out.flush();
out.close();
}
}