首先基于 springboot 实现的,其他场景下可以引入相应的 jar 包后进行整合。
首先写入一个方法,方法的参数为传入的文件,方法的返回值自定义,这里返回类型为 String ,返回文件的存储地址。
public String uploadToLocal(MultipartFile file){ }接着在方法中进行文件的具体存取操作。
首先获取上传文件的原始名称:
String originName = file.getOriginalFilename();接着可以指定只能上传 pdf,doc,docx?类型的文件,这里需要先找出文件的后缀来判断上传文件的类型是否合法:
先将指定的后缀存在 set 集合中, set 集合的底层是哈希表,时间复杂度为 O(1)
Set<String> set = new HashSet<>(); set.add(".pdf"); set.add(".doc"); set.add(".docx"); set.add(".jpg");接着找出文件的后缀,首先遍历获取的原始文件名,通过下标遍历这个原始名称,找到第一个"."后结束遍历,然后调用 String.subString(int index) 得到字符串从 index (包括)一直到后面所有的字符串,得到的字符串就是文件的后缀。
int count = 0; for(int i = 0; i < originName.length(); i++){ if(originName.charAt(i) == '.'){ count = i; break; } } String endName = originName.substring(count);同时也可以获取到文件类型,比如 ".pdf" 将"."去掉得到类型?pdf
String fileType = originName.substring(count + 1);再判断文件是否是合法类型,不合法则直接返回错误信息:
if(!set.contains(endName)){ return new String("上传的文件类型错误,只能上传pdf,doc,docx,jpg类型的文件"); }如果文件类型合法,进行接下来的操作。
首先确定文件的保存路径,可以自定义。这里直接保存在项目父目录下,加入项目叫 test,路径为
test/files/文件类型/保存文件时候的时间(yyyyMMdd)年月日/文件原始名称
这就需要获取当天的日期并格式化为yyyyMMdd格式,并获取文件类型。
路径采用拼接的方式,先获取当前项目的路径然后一步步拼接:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String format = sdf.format(new Date()); String savePath = System.getProperty("user.dir") + "\\" + "files" + "\\" + fileType + "\\" + format;最后进行文件的保存,文件保存过程中可能会出现异常,因此用try...catch:
try { file.transferTo(new File(folder,saveName)); String filePath = savePath + "\\" + saveName; return new String("文件路径为:" + filePath); } catch (IOException e){ return new String(e.getMessage()); }最后返回的String为文件的存储地址,即保存路径 + 文件名。
接下来是方法的完整代码:
public String uploadToLocal(MultipartFile file){ // 获取文件原本的名字 String originName = file.getOriginalFilename(); // 判断文件是否是pdf文件 Set<String> set = new HashSet<>(); set.add(".pdf"); set.add(".doc"); set.add(".docx"); // 取出文件的后缀 int count = 0; for(int i = 0; i < originName.length(); i++){ if(originName.charAt(i) == '.'){ count = i; break; } } String endName = originName.substring(count); //取出文件类型 String fileType = originName.substring(count + 1); //文件类型 if(!set.contains(endName)){ return new String("上传的文件类型错误,只能上传pdf,doc,docx类型的文件"); } // 创建保存路径 //日期格式 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String format = sdf.format(new Date()); String savePath = System.getProperty("user.dir") + "\\" + "files" + "\\" + fileType + "\\" + format; // 保存文件的文件夹 File folder = new File(savePath); // 判断路径是否存在,不存在则自动创建 if(!folder.exists()){ folder.mkdirs(); } String saveName = originName; try { file.transferTo(new File(folder,saveName)); String filePath = savePath + "\\" + saveName; return new String("文件路径为:" + filePath); } catch (IOException e){ return new String(e.getMessage()); } }方法可用作工具类,也可以直接用作后端接口。
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。 |
标签: #java上传文件到本地 #首先基于 #springboot #实现的其他场景下可以引入相应的 #jar #包后进行整合 #string