上传文件
Posted xymaxbf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了上传文件相关的知识,希望对你有一定的参考价值。
@RequestMapping(value = "/upload", method = RequestMethod.POST) public String upload(MultipartFile file, HttpServletRequest request) { String path = localpath + "\"; String date = sdf.format(new Date()); String routepath = path + date; String url = httpurl.getRequestPrefix(request);//项目地址 String[] files = file.getOriginalFilename().split("\.");//获取上传文件的后缀 String filename = UUID.randomUUID().toString().replaceAll("-", "");//给文件重新命名 String name = routepath + "\" + filename + "." + files[1]; String besuchurl = url + "/static/" + date.replaceAll("\\", "/") + "/" + filename + "." + files[1];//访问路径 File file2 = new File(routepath); if (!file.isEmpty()) {//判断文件是否为空 if (!file2.exists()) {//判断文件夹是否为空 file2.mkdirs(); } else { try { file.transferTo(new File(name)); } catch (Exception e) { e.printStackTrace(); } } } return besuchurl; }
上传多个文件
@RequestMapping(value = "/uploads", method = RequestMethod.POST) public toJSON uploads(MultipartFile[] filees, HttpServletRequest request) { ArrayList list = new ArrayList(); for (int i = 0; i < filees.length; i++) { String path = localpath + "\"; String date = sdf.format(new Date()); String routepath = path + date; String url = httpurl.getRequestPrefix(request);//项目地址 String[] files = filees[i].getOriginalFilename().split("\.");//获取上传文件的后缀 String filename = UUID.randomUUID().toString().replaceAll("-", "");//给文件重新命名 String name = routepath + "\" + filename + "." + files[1]; String besuchurl = url + "/static/" + date.replaceAll("\\", "/") + "/" + filename + "." + files[1];//访问路径 File file2 = new File(routepath); if (!filees[i].isEmpty()) {//判断文件是否为空 if (!file2.exists()) {//判断文件夹是否为空 file2.mkdirs(); } else { try { filees[i].transferTo(new File(name)); } catch (Exception e) { e.printStackTrace(); } } } fileurl fileurl=new fileurl(); fileurl.setId(files[0]); fileurl.setUrl(besuchurl); list.add(fileurl); } return new toJSON("ok", "成功", list); }
以上是关于上传文件的主要内容,如果未能解决你的问题,请参考以下文章
ajaxFileUpload上传带参数文件及JS验证文件大小