form前台
<input type="file" name="file" />
function checkinfo(param){
var proid=/*[[${applypro.proid}]]*/;
applyproform.action="../middleevaluate/insertmsg"+proid+"/"+param;
applyproform.submit();
}
提交所有参数
@RequestMapping(value = "/insertmsg{status}")
public String insertmsg(@PathVariable("status") String status ,@RequestParam("file") MultipartFile[] files,Model model, HttpServletRequest request,@ModelAttribute("dto") ApplyproDto pr,HttpServletResponse response){
response.setHeader("X-Frame-Options", "SAMEORIGIN");
//获取用户登录名
UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String loginname=userDetails.getUsername();
User userInfo = uiservice.findByLoginName(loginname);
pr.setProid(ToolUtil.getUUID());
pr.setUserid(userInfo.getUserId());
pr.setUserdept(userInfo.getDeptid());
pr.setIschild("1");
applyproservice.insertAndsaveApply(pr);
if(files!=null&&files.length>0){
//循环获取file数组中得文件
for(int i = 0;i<files.length;i++){
MultipartFile file = files[i];
//保存文件
saveApplyproFile(file,pr);
}
}
return "redirect:/applypro/msglist";
}
上传正式方法
private void saveApplyproFile(MultipartFile file, ApplyproDto pr) {
ApplyprofileDto applyproFileDto=new ApplyprofileDto();
// String rootPath="e:/shzz/shenbaofile";
String rootPath = shenbaofilePath;
File rootPathTest=new File(rootPath);
if (!rootPathTest.exists()) {
rootPathTest.mkdirs();
}
String fileName = file.getOriginalFilename();
String serverFileName = "";
if(fileName!=null&&!"".equals(fileName)){
serverFileName = System.currentTimeMillis()+fileName.substring(fileName.indexOf("."), fileName.length());
byte[] bytes;
try {
bytes = file.getBytes();
File outfile=new File(rootPath+File.separator+serverFileName);
FileCopyUtils.copy(bytes, outfile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
applyproFileDto.setId(ToolUtil.getUUID());
applyproFileDto.setApplypro(new Applypro(pr));
applyproFileDto.setFilename(fileName);
applyproFileDto.setFileurl(rootPath+"/"+serverFileName);
applyproFileService.insertapplyproFile(applyproFileDto);
}
}
下载附件
前台
function downloadmpg(id){
window.open("../middleevaluate/downfile"+id,"_blank");
}
@RequestMapping(value="downfile{id}")
public void applyprofileDown(HttpServletRequest request,HttpServletResponse response,@PathVariable("id") String id)
{
//获取要下载的文件
Applyprofile applyproFile =applyproFileService.findApplyproFileById(id);
String fileName="",fileurl="";
if(applyproFile!=null){
fileName=applyproFile.getFilename();
fileurl=applyproFile.getFileurl();
File file = new File(fileurl);
byte[] buf = new byte[1024 * 1024 * 10];
int len = 0;
ServletOutputStream ut = null;
BufferedInputStream br = null;
response.reset();
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "must-revalidate, no-transform,max-age=0");
response.setDateHeader("Expires", 0L);
String userAgent = request.getHeader("User-Agent");
boolean ie = (userAgent.toLowerCase().indexOf("msie") > -1 || userAgent.toLowerCase().indexOf("rv:11") > -1);
boolean isIE = (userAgent != null) && ie;
String displayFilename = file.getName();
response.setContentType("application/x-download");
if (isIE) {
try {
displayFilename = URLEncoder.encode(displayFilename, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setHeader("Content-Disposition", "attachment;filename=\"" + displayFilename + "\"");
} else {
try {
displayFilename = new String(displayFilename.getBytes("UTF-8"), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setHeader("Content-Disposition", "attachment;filename=" + displayFilename);
}
try {
br = new BufferedInputStream(new FileInputStream(file));
ut = response.getOutputStream();
while ((len = br.read(buf)) != -1)
ut.write(buf, 0, len);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
删除附件
前台
function deleteFilempg(id){
$("#"+id).remove();
var applyprofile = {};
var applyprofileArray = new Array(1);
applyprofile.fileid=id;
applyprofileArray[0] = applyprofile;
$.ajax({
url : "../middleevaluate/deleteFile",
dataType: "json",
data:{
models : JSON.stringify(applyprofileArray)
},
type:"POST",
success: function(result) {
if(result.ajaxResultJson.success){
alert(result.ajaxResultJson.msg);
}else{
alert(result.error);
}
},
error: function(result) {
alert("系统异常");
}
});
return false;
}
@RequestMapping(value = "/deleteFile", method = RequestMethod.POST)
public AjaxResultJson deleteFile(Model model,@RequestParam("models") String models)
{
AjaxResultJson result = new AjaxResultJson();
result.setSuccess(false);
List<ApplyprofileDto> list = new ArrayList<ApplyprofileDto>();
if(models!=null && models.length()>0)
{
try
{
list = objectMapper.readValue(models,new TypeReference<List<ApplyprofileDto>>() {});
}
catch (JsonParseException e)
{
log.error("JsonParseException{}:", e.getMessage());
model.addAttribute("error", e.getMessage());
}
catch (IOException e)
{
log.error("IOException{}:", e.getMessage());
model.addAttribute("error", e.getMessage());
}
}
if (!model.containsAttribute("error"))
{
try {
if(list!=null && list.size()>0){
ApplyprofileDto dto = list.get(0);
dto=new ApplyprofileDto(applyproFileService.findApplyproFileById(dto.getId()));
File file=new File(dto.getFileurl());
file.delete();
applyproFileService.deleteApplyproFileById(dto.getId());
result.setMsg("删除成功!");
result.setSuccess(true);
}
} catch (Exception e) {
result.setMsg("删除失败,文件不存在 !");
result.setSuccess(false);
log.error("Exception{}:", e.getMessage());
model.addAttribute("error", e.getMessage());
result.setMsg( e.getMessage());
}
}
return result;
}