File upload using virtual path for project deployment and user resource separation

Source: Internet
Author: User
Tags log log

The following tool classes are used to implement user resource and project separation:

Save Path Tool class
 Packagecn.gukeer.common.utils;ImportCom.github.pagehelper.StringUtil;ImportOrg.apache.commons.logging.Log;Importorg.apache.commons.logging.LogFactory;ImportOrg.springframework.core.io.ClassPathResource;ImportOrg.springframework.web.multipart.MultipartFile;ImportJava.io.*;Importjava.util.Properties;ImportJava.util.StringTokenizer;/*** File Management Help class that handles files other than apps, such as photos, mail attachments, etc. that do not depend on the existence of the app. Note: The file path inside is based on the VFS root path in addition to the special instructions * *@authorGuowei*/ Public Abstract classVfsutil {Private StaticLog log = Logfactory.getlog (vfsutil.class); /*** VFS Root path (last no/No)*/    Private StaticString Vfs_root_path; Static {        Try{Readvfsrootpath ();//assigning an initial value to Vfs_root_path}Catch(Exception e) {log.error ("Error reading configuration file!" ", E); }    }    /*** Read VFS path configuration file*/    Private Static voidReadvfsrootpath () {String key=NULL; if(System.getproperty ("Os.name"). toUpperCase (). IndexOf ("WINDOWS")! =-1) {Key= "Vfsroot.windows"; } Else{Key= "Vfsroot.linux"; }        Try{Properties P=NewProperties (); InputStream instream=NewClasspathresource ("/db.properties"). getInputStream ();            P.load (instream); Vfs_root_path=P.getproperty (key); } Catch(Exception E1) {Vfs_root_path= ""; Log.error ("[Vfsroot Path read] configuration file mode Error! ", E1); }        if(Stringutil.isempty (Vfs_root_path)) {if(System.getproperty ("Os.name"). toUpperCase (). IndexOf ("WINDOWS")! =-1) {Vfs_root_path= "c:/gukeer/vfsroot/"; } Else{Vfs_root_path= "/opt/gukeer/vfsroot/"; }        }    }    /*** Get the current Vfsrootpath * *@return     */     Public StaticString Getvfsrootpath () {returnVfs_root_path; }    /*** Get file input stream * *@paramfile *@paramFileStream *@return     */     Public StaticInputStream getinputstream (File file,BooleanFileStream) {        if(FileStream = =true) {//working with file streamsFileInputStream fin =NULL; Try{fin=Newfileinputstream (file); } Catch(FileNotFoundException e) {if(log.isdebugenabled ()) {log.debug (e); } String msg= "Cannot find the specified file [" + file.getname () + "]. "; if(log.isdebugenabled ()) {log.debug (msg); }                Throw Newfileoperationexception (MSG, E); }            returnfin; } Else{//using memory StreamsInputStream in =NULL; if(File! =NULL&& File.canread () &&File.isfile ()) {                Try{Bytearrayoutputstream buffer=NewBytearrayoutputstream (); FileInputStream Stream=Newfileinputstream (file); Bufferedinputstream bin=NewBufferedinputstream (stream); intLen = 0; byte[] B =New byte[1024];  while(len = Bin.read (b))! =-1) {Buffer.write (b,0, Len);                    } stream.close (); Inch=NewBytearrayinputstream (Buffer.tobytearray ()); } Catch(Exception e) {String msg= "Cannot read file [" + file.getname () + "]"; if(log.iserrorenabled ()) {Log.error (msg, E); }                    Throw Newfileoperationexception (MSG, E); }            } Else{String msg= "Not a file or file is unreadable [" + file.getname () + "]"; if(log.isdebugenabled ()) {log.debug (msg); }                Throw NewFileoperationexception ("Not a file or file is not readable"); }            returnIn ; }    }}
Precautions:
① Configure the properties file within the Resources folder, including Vfsroot path information (Windows and Linux two paths), modify the upload method so that users upload files and other resources are stored in the Vfsroot path, and the picture storage path is saved in the database to facilitate the client to read and use;Properties Configuration Demo:   
#db Configjdbc.schema=gk_platformjdbc.driver=Com.mysql.jdbc.Driverjdbc.url= Jdbc:mysql://localhost:3306/test?useunicode=true&characterencoding=utf-8& Usejdbccomplianttimezoneshift=true&uselegacydatetimecode=false&servertimezone=utc&usessl=false jdbc.username=Rootjdbc.password=123456vfsroot.windows=c:/platform/vfsroot/  Vfsroot.linux=/opt/platform/vfsroot/
② because the client cannot directly request access to resources located on the physical path of the server, the front-end page displays pictures and other resources in a stream-read manner, adding the following method to the controller:
/*** Read Picture file * *@paramResponse *@throwsException*/@RequestMapping ("/website/showpicture")     Public voidShowpicture (httpservletresponse response, String Picpath)throwsException {File file=NewFile (Vfs_root_path +Picpath);        if(!file.exists ()) {Logger.error ("File not found [" + Vfs_root_path + Picpath + "]"); return; } response.setcontenttype ("Multipart/form-data"); InputStream Reader=NULL; Try{Reader= Vfsutil.getinputstream (file,true); byte[] buf =New byte[1024]; intLen = 0; OutputStream out=Response.getoutputstream ();  while(len = Reader.read (BUF))! =-1) {out.write (buf,0, Len);        } out.flush (); } Catch(Exception ex) {Logger.error ("An error occurred while displaying the picture:" +ex.getmessage (), ex); } finally {            if(Reader! =NULL) {                Try{reader.close (); } Catch(Exception ex) {Logger.error ("Close file out of error", ex); }            }        }    }

Front JSP page Call: ${image.imagesurl}";, for example:

'/>

The URL of the database to save the picture is/website/showpicture?picpath=/images/upload/image/20160608/1465355183063.png

File upload using virtual path for project deployment and user resource separation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.