Springboot 简单实现文件上传
一.js
$("button[name='uploadbtn']").click(function () {
var hid = this.id;
var uid = loginid;
$('#uploadmodal').modal("show");
$("button[name='uploadbtn2']").click(function () {
var formData = new FormData(document.getElementById("upload-form"));
$.ajax({
url: "homework/upload",
method: 'POST',
data: formData,
contentType: false,
processData: false,
success: function (resp) {
if(resp.result!=null){
$.getJSON("homework/saveDetails/"+uid+"/"+hid+"/"+resp.result , function (json) {
if ("outtime"==json.rs){
alert("已超时");
}else if("fail"==json.rs){
alert("失败");
}else{
alert(" 添加成功");
$('#modalhwdetail2').modal('hide');
}
})
}else{
alert("上传失败");
}
}
});
})
})
二.Controller
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public Map upload(@RequestParam MultipartFile myFile, HttpSession session) throws IOException {
String originalFilename = myFile.getOriginalFilename();
int pos = originalFilename.lastIndexOf(".");
String suffix = originalFilename.substring(pos);
String realPath = "D:/tmp";
String uuid = UUID.randomUUID().toString();
String fullPath = realPath + File.separator + uuid + suffix;
String homeworkid=File.separator + uuid + suffix;
InputStream in = null;
try {
in = myFile.getInputStream();
OutputStream out = new FileOutputStream(new File(fullPath));
int len = 0;
byte[] buf = new byte[3 * 1024];
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
Map map= new HashMap();
map.put("result",homeworkid);
return map;
}
@RequestMapping("saveDetails/{uid}/{hid}/{result}")
public Map saveDetails(@PathVariable("uid") String uid, @PathVariable("hid") String hid,@PathVariable("result") String homeworkid) {
Map map = new HashMap();
int rs = hs.savedetails(uid, hid,homeworkid);
if (rs > 0) {
map.put("rs", "success");
} else if (rs == -1) {
map.put("rs", "outtime");
} else {
map.put("rs", "fail");
}
return map;
}
三.Service
public int savedetails(String uid, String hid,String homeworkid) {
int rs = 0;
List<Homework> list = hr.findAllById(hid);
if (new Date(System.currentTimeMillis()).getTime() > list.get(0).getFinishTime().getTime()) {
rs = -1;
} else {
if (dd.queryfindexist(uid, hid).size() > 0) {
dd.queryuploadDTOListMap2(uid, hid, homeworkid,new Timestamp(new java.util.Date().getTime()));
rs = 1;
} else {
dd.queryuploadDTOListMap(uid, hid, homeworkid,new Timestamp(new java.util.Date().getTime()));
rs = 1;
}
}
return rs;
}