springMVC实现文件上传

1、相关配置省略

2、前端

<form method="post" action="/fileupload"  enctype="multipart/form-data" class="form-horizontal">

<input type="file" id="excel-file" name="file">

<input type="submit" value="上传"/>

</form>

3、控制器:

    @RequestMapping("/fileupload")
    @ResponseBody
    public Object pexAttachUpload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request){
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
            String date = df.format(new Date());
            String path = request.getSession().getServletContext().getRealPath("upload"+File.separator+date);  
            
            String fileName = file.getOriginalFilename();  
            int code = 0;
            String msg = "上传失败!";
            JSONObject json = new JSONObject();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
            String Rname=sdf.format(new Date());        
            int i=fileName.lastIndexOf(".");//原名称里倒数第一个"."在哪里
            String ext=fileName.substring(i+1);//取得后缀,及"."后面的字符
            String name=Rname+"."+ext;//拼凑而成
            File targetFile = new File(path, name);
             if(!"xls".equals(ext) && !"xlsx".equals(ext)){
                 json.put("code", code);
                 json.put("msg", "文件格式不正确,请重新上传!");
                 return json;  
            }
            if(!targetFile.exists()){  
                targetFile.mkdirs();  
            }
           
            //保存  
            try {  
                file.transferTo(targetFile);
                code=1;
                msg="上传成功";
            } catch (Exception e) {  
                e.printStackTrace();  
            }
            
            json.put("code", code);
            json.put("msg", msg);
            json.put("myfile", "upload"+File.separator+date+File.separator+name);
            
            return json;
    }

删除文件:

@RequestMapping("/deletefile")
    @ResponseBody
    public Object deleteuploadfile(@RequestParam(value="myfilepath") String myfilepath,HttpServletRequest request){
           String path = request.getSession().getServletContext().getRealPath("");
            String filePath = path + File.separator + myfilepath;
            int code = 1;
            File file = new File(filePath);    
            if(file.exists()){
                file.delete();
            }           
            JSONObject json = new JSONObject();
            json.put("code", code);            
            return json;
    }

 

posted @ 2015-10-08 14:27  郑州peak  阅读(213)  评论(0编辑  收藏  举报