File Upload uses virtual paths to separate project deployment from user resources and deploy File Upload
The following tool class is used to separate user resources from projects:
Save path tool
Package cn. gukeer. common. utils; import com. github. pagehelper. stringUtil; import org. apache. commons. logging. log; import org. apache. commons. logging. logFactory; import org. springframework. core. io. classPathResource; import org. springframework. web. multipart. multipartFile; import java. io. *; import java. util. properties; import java. util. stringTokenizer;/*** file management help class to process files outside of the application, such as photos and email attachments, and other files that do not depend on the application. Note: The file paths are based on the VFS root path ** @ author guowei */public abstract class VFSUtil {private static Log log = LogFactory. getLog (VFSUtil. class);/*** VFS root path (no/number at the end) */private static String VFS_ROOT_PATH; static {try {readVFSRootPath (); // assign the initial value to VFS_ROOT_PATH} catch (Exception e) {log. error ("An error occurred while reading the configuration file! ", E) ;}}/*** read the VFS path configuration file */private static void readVFSRootPath () {String key = null; if (System. getProperty ("OS. name "). toUpperCase (). indexOf ("WINDOWS ")! =-1) {key = "vfsroot. windows ";} else {key =" vfsroot. linux ";} try {Properties p = new Properties (); InputStream inStream = new ClassPathResource ("/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 static String getVFSRootPath () {return VFS_ROOT_PATH ;} /*** get the file input stream ** @ param File * @ param fileStream * @ return */public static InputStream getInputStream (file, boolean fileStream) {if (fileStream = true) {// use the file stream FileInputStream fin = null; Try {fin = new FileInputStream (file);} catch (FileNotFoundException e) {if (log. isDebugEnabled () {log. debug (e);} String msg = "the specified file [" + file cannot be found. getName () + "]. "; If (log. isDebugEnabled () {log. debug (msg);} throw new FileOperationException (msg, e);} return fin;} else {// use the memory stream InputStream in = null; if (file! = Null & file. canRead () & file. isFile () {try {ByteArrayOutputStream buffer = new ByteArrayOutputStream (); FileInputStream stream = new FileInputStream (file); BufferedInputStream bin = new BufferedInputStream (stream); int len = 0; byte [] B = new byte [1024]; while (len = bin. read (B ))! =-1) {buffer. write (B, 0, len);} stream. close (); in = new ByteArrayInputStream (buffer. toByteArray ();} catch (Exception e) {String msg = "file cannot be read [" + file. getName () + "]"; if (log. isErrorEnabled () {log. error (msg, e);} throw new FileOperationException (msg, e) ;}} else {String msg = "not a file or the file cannot be read [" + file. getName () + "]"; if (log. isDebugEnabled () {log. debug (msg);} throw new FileOperationException ("not a file or file unreadable");} return in ;}}}
Note:
① Configure the properties file in the resources folder, which contains the vfsroot path information (windows and linux paths). Modify the upload method so that the files uploaded by the user and other resources are stored in the vfsroot path, save the image storage path in the database for 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=falsejdbc.username=rootjdbc.password=123456vfsroot.windows=C:/platform/vfsroot/vfsroot.linux=/opt/platform/vfsroot/
② Because the client cannot directly request access to resources located in the physical path of the server, the front-end page displays images and other resources using stream reading. Add the following method to the controller:
/*** Read the image file ** @ param response * @ throws Exception */@ RequestMapping ("/website/showPicture") public void showPicture (HttpServletResponse response, String picPath) throws Exception {File file = new File (VFS_ROOT_PATH + picPath); if (! File. exists () {logger. error ("file [" + VFS_ROOT_PATH + picPath + "]"); return;} response. setContentType ("multipart/form-data"); InputStream reader = null; try {reader = VFSUtil. getInputStream (file, true); byte [] buf = new byte [1024]; int len = 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 image:" + ex. getMessage (), ex);} finally {if (reader! = Null) {try {reader. close () ;}catch (Exception ex) {logger. error ("file stream close error", ex );}}}}
Front-end jsp page call: $ {image. imagesUrl}">, for example:
The URL of the image saved in the database is/website/showPicture? PicPath =/images/upload/image/20160608/1465355183063 .png