here is a file Upload tool class, the versatility is very strong. Nonsense not much to say, went straight to the subject. If you have questions or errors, please correct the exchange.
public class Fileuploadutils {
private static final Logger Logger = Loggerfactory.getlogger (Fileuploadutils.class);
public static String Getuploadpath (HttpServletRequest request) {
return Getapplicationpath (Request) +constens.upload_folder;//contens.upload_folder is a constant UPLOAD
}
public static String Getapplictionpath (HttpServletRequest request) {
Return Request.getsession (). Getservletcontext (). Getrealpath ("/");
}
Save File
public static String Saveuploadfiletodisk (multipartfile multipartfile,httpservletrequest request,string tempDir) Throws exception{
InputStream is = null;
OutputStream OS = null;
String filePath = null;
String fileName = null;
String suffix = null;
String tempname = null;
try{
is = Multipartfile.getinputstream ();
FileName = Multipartfile.getoriginalfilename ();
suffix = filename.substring (Filename.indexof ("."));
Tempname = Idutils.uuid32 () +suffix;//idutils.uuid32 () an algorithm that generates a unique ID;
FilePath = CreateFile (Request,tempname,tempdir);
OS = new FileOutputStream (FilePath);
Byte[] b = new byte (1024);
while (Is.read (b,0,b.length) >-1) {
Os.write (b);
}
}catch (IOException e) {
E.printstacktrace ();
}finally{
if (OS!= null) {
Os.flush ();
Os.close ();
}
if (is!= null) {
Is.close ();
}
}
Logger.info ("File Upload path" +filepath);
return TempDir + file.separator + tempname;//relative path
Return Filepath.replace (GetFilePath (), "");
}
public static String CreateFile (httpservletrequest request,string filename,string tempdir) throws exception{
TempDir = Stringutils.isnotblank (tempdir)? TempDir:UUID.randomUUID (). toString ();
Date Nowtime = new Date (System.currenttimemillis ());
SimpleDateFormat sdformatter = new SimpleDateFormat ("Yyyy-mm-dd");
String retstrformatnowdate = Sdformatter.format (nowtime);
string[] timetemp = Retstrformatnowdate.split ("-");
String path = "";
Path = GetFilePath () +file.separator+timetemp[0]+file.separator+timetemp[1]+file.separator+timetemp[2]+ File.separator+tempdir;
Logger.info ("Temporary folder:" +path);
File Filetemp = new file (path);
if (!tempfile.exists ()) {
Tempfile.mkdirs;
}
String diskfilestr = path + File.separator + fileName;
Logger.info ("Upload file path" +path);
File Diskfile = new file (DISKFILESTR);
if (!diskfile.exists ()) {
Diskfile.createnewfile ();
}
return diskfilestr;
}
}