SpringMVC文件上传

来源:互联网 发布:淘宝客服怎么登陆千牛 编辑:程序博客网 时间:2024/04/29 13:56

一、代码部分

0x00

@RequestMapping("/file/uploadFile")public @ResponseBody JsonResult uploadFile(@RequestParam MultipartFile myfile, HttpServletRequest request){    if(myfile==null || myfile.isEmpty()) return new JsonResult(false,"附件不得为空");try {String extName = "";        String fileName = myfile.getOriginalFilename();        if(fileName != null && !"".equals(fileName.trim())){        extName = fileName.substring(fileName.lastIndexOf("."));        }        if(!checkCommenFileType(extName))        return new JsonResult(false,"仅允许上传doc、docx文档");         String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");        File rootFile = new File(realPath);        if(!rootFile.exists())             rootFile.mkdirs();        DateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ssSSS");  Calendar calendar = Calendar.getInstance();        String newName = df.format(calendar.getTime());        //这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的             //FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename()));        myfile.transferTo(new File(realPath, newName+extName));        } catch (Exception e) {e.printStackTrace();return new JsonResult(false,"上传失败");}      return new JsonResult(true,"上传成功");}

0x01

<pre name="code" class="java">

@RequestMapping(value = "/flie/ajax/file_add", method = RequestMethod.POST)public void uploadFile(HttpServletResponse response,HttpServletRequest request,@RequestParam(value = "file", required = false) MultipartFile file)throws IOException {byte[] bytes = file.getBytes();// 文件名称String fileName = file.getOriginalFilename();String uploadDir = request.getSession().getServletContext().getRealPath("/")+ Constants.FILE_UPLOAD_PATH;/** 获取文件的后缀 **/String suffix = file.getOriginalFilename().substring(fileName.lastIndexOf("."));File dirPath = new File(uploadDir);if (!dirPath.exists()) {dirPath.mkdirs();}String sep = System.getProperty("file.separator");String fileUrl = UuidFactory.getUuid() + suffix;FileCopyUtils.copy(bytes, new File(dirPath+fileUrl));}

二、前端

0x00

 <form id="myForm" name="myForm" enctype="multipart/form-data">                <li><input name="myfile" id="lecture" type="file" class="wby"/></li>                <li><input type="submit" value="上 传"  class="cinput"/></li>                </form>



0x01

<input type="file" name="fileName" id="file_upload" value="" /><a href="javascript:void(0)" onclick="$('#file_upload').uploadify('upload', '*');" >保存</a><a href="javascript:void(0)" onclick="javascript:$('#file_upload').uploadify('stop');">取消</a>
$("#file_upload").uploadify({'method' : 'post','swf' : '${ctx}/static/js/uploadify/uploadify.swf','uploader' : '${ctx}/car/ajax/transport_file_add','auto' : false,'buttonText' : '选择文件','fileTypeExts' : '*.jpg;*.jpge;*.gif;*.png','fileSizeLimit' : '4MB','queueSizeLimit' : '10','fileObjName' : 'file',//controller中变量名//选择上传文件后调用'onSelect' : function(file) {},'onUploadStart' : function(file) {$("#file_upload").uploadify("settings", "formData", {'description' : $("#description").val(),"secondType" : $("#secondType").val(),"tid" : $("#tid").val()});//在onUploadStart事件中,也就是上传之前,把参数写好传递到后台。  },//检测浏览器是否已安装flash空间'onFallback' : function() { //Flash无法加载错误alert("您未安装FLASH控件,无法上传!请安装FLASH控件后再试。");},//上传错误后'onUploadError' : function(file, errorCode, errorMsg) { //上传失败alert(file.name + "上传失败,错误信息:" + errorMsg);},//上传成功后'onUploadSuccess' : function(file, data, response) {alert(file.name + ' 上传成功! ');$.listTransportFile('${ctx}', 1);}});




0 0