這是upload類的方法:
public class Upload {
public static String upload(FormFile formfile,String dirPath,int port){
String savePath="";
String ip="";
try{
String filename = formfile.getFileName().trim(); // 檔案名稱
if (!"".equals(filename)) {
InputStream ins = formfile.getInputStream();
String currentPath=dirPath+ File.separatorChar + filename; //檔案儲存路徑
OutputStream os = new FileOutputStream(currentPath);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
boolean isWindows=isWindowsOS(); //判斷是否是windows系統
if(isWindows){
InetAddress address=InetAddress.getLocalHost();
ip=address.getHostAddress(); //擷取ip地址
System.out.println("windows ip地址:"+ip);
}
else{ //如果是Linux系統
ip=Tools.getLinuxIP();
System.out.println("linux ip地址:"+ip);
}
savePath="http://"+ip+":"+port+"/channelProject/upload/"; //儲存到資料庫的地址,圖片上傳到伺服器端
savePath+=filename;
os.close();
ins.close();
}
}
catch (Exception e) {
e.printStackTrace();
System.out.println("上傳出現錯誤!!");
}
return savePath;
}
/*
* @return true---是Windows作業系統
*/
public static boolean isWindowsOS(){
boolean isWindowsOS = false;
String osName = System.getProperty("os.name");
if(osName.toLowerCase().indexOf("windows")>-1){
isWindowsOS = true;
}
return isWindowsOS;
}
}