| | |
| | | package com.lunhan.xxx.common.util; |
| | | |
| | | import org.springframework.web.multipart.MultipartFile; |
| | | |
| | | import java.io.*; |
| | | import java.nio.charset.Charset; |
| | | import java.text.DateFormat; |
| | | import java.text.SimpleDateFormat; |
| | | import java.util.Date; |
| | | import java.util.Random; |
| | | import java.nio.charset.StandardCharsets; |
| | | |
| | | /** |
| | | * 文件工具类 |
| | |
| | | } |
| | | |
| | | /** |
| | | * 文件上传 |
| | | * @return |
| | | */ |
| | | public static String uploadUtil(MultipartFile myFile, String fileUrlName) { |
| | | String urlName=""; |
| | | try { |
| | | DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS"); |
| | | //文件名称 |
| | | String name = df.format(new Date()); |
| | | |
| | | Random r = new Random(); |
| | | for (int i = 0; i < 3; i++) { |
| | | name += r.nextInt(10); |
| | | } |
| | | int idx = myFile.getOriginalFilename().lastIndexOf("."); |
| | | String ext = myFile.getOriginalFilename().substring(idx); |
| | | //保存文件 File位置 (全路径) /upload/fileName |
| | | |
| | | String url = "/" + fileUrlName+"/" ; |
| | | //相对路径 |
| | | String path = name + "." + ext; |
| | | File file = new File(url); |
| | | if (!file.exists()) { |
| | | file.mkdirs(); |
| | | } |
| | | myFile.transferTo(new File(url + path)); |
| | | urlName=path; |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | } |
| | | return urlName; |
| | | } |
| | | |
| | | /** |
| | | * 删除文件 |
| | | * @param path |
| | | */ |
| | |
| | | file.delete(); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 读取流内容 |
| | | * @param inputStream 流 |
| | | */ |
| | | public static String readFileContent(InputStream inputStream) { |
| | | return FileUtil.readFileContent(inputStream, null); |
| | | } |
| | | |
| | | /** |
| | | * 读取流内容 |
| | | * @param inputStream 流 |
| | | * @param charset 编码格式 |
| | | */ |
| | | public static String readFileContent(InputStream inputStream, Charset charset) { |
| | | if(null==charset) { |
| | | charset = StandardCharsets.UTF_8; |
| | | } |
| | | StringBuilder localStrBulider = new StringBuilder(); |
| | | try (InputStreamReader inputStreamReader=new InputStreamReader(inputStream, charset)){ |
| | | BufferedReader bufferReader = new BufferedReader(inputStreamReader); |
| | | String lineStr; |
| | | while((lineStr = bufferReader.readLine()) != null) { |
| | | localStrBulider.append(lineStr); |
| | | } |
| | | bufferReader.close(); |
| | | } catch (IOException e) { |
| | | //TODO log |
| | | } |
| | | return localStrBulider.toString(); |
| | | } |
| | | } |