1. 程式人生 > >springboot圖片上傳工具類

springboot圖片上傳工具類

tostring file path boot int eal uuid domu != rep

package com.wiscom.ism.webapi.ismUtil;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@Component
public class FileUploadUtil { //存儲路徑 public String getPath(){ File path = null; try { path = new File(ResourceUtils.getURL("classpath:").getPath()); if (!path.exists()){ path.mkdirs(); } } catch (FileNotFoundException e) { e.printStackTrace(); } String imagesPath
= path.getAbsolutePath(); return imagesPath; } //上傳存到硬盤 public boolean upLoadImage(String imagesPath,String pathImg,InputStream fileInputStream){ File file = new File(imagesPath,"static/"+pathImg); try { if (fileInputStream != null){ FileUtils.copyInputStreamToFile(fileInputStream, file); } }
catch (IOException e) { e.printStackTrace(); return false; } return true; } //生成名字 public String imageName(String image){ String imageName =null; //生成uuid作為文件名稱 String uuid = UUID.randomUUID().toString().replaceAll("-","").substring(0,10); //後綴 String imgType =image.substring(image.lastIndexOf(".")+1,image.length()); if ("gif".equals(imgType) || "jpg".equals(imgType) || "png".equals(imgType)){ imageName=uuid+"."+imgType; } return imageName; } }

springboot圖片上傳工具類