Java Web--fileupload Plugin Web page file Management __web

Source: Internet
Author: User
Tags create directory save file solr java web

Introduction : In the actual Web project, we often encounter this situation, in the background management platform, backstage managers need to upload some files, such as promotional activity pictures and activities copy files to the server, and then spread to the product promotion home page, complete the dynamic deployment of product-related sales activities function. Usually, in the case of large traffic, we will consider the file on a separate file server, using a Third-party Distributed File system to complete the deployment of the relevant file server, such as my personal use of fastdfs+solr+ The ZEROMQ framework completes the system of distributed File System Management from server to client side. Then how to deal with the storage and search of these files when the hardware environment is relatively scarce. This is what this article describes.
Web file management, mainly related to the following aspects: File Upload file storage organization way Web File acquisition method
Among them, in particular, the organization of file storage is to be.
First, define a class that stores network files locally, establishes the appropriate file organization structure, and provides a Web Access interface. This class is named Filemanager.java, first defining how the class is constructed, and the private variables of the class

public class FileManager {public
    static final String error = ' ERROR ';
    The public static final String none = "None";
    Root directory
    private String basepath;
    /*//Custom Storage Root Path public
    FileManager (String basepath) {
        this.basepath = basepath;
    } *
    ///default storage root Path public
    FileManager () {
        This.basepath = This.getclass (). GetResource ("/"). GetPath (). Split ("WebApps") [0]+ "Webapps/file";
    }

    Public String Getbasepath () {return
        This.basepath
    }
    ...
}

Here's how to customize the way a store path is commented, but instead use a fixed folder to store the file, which refers to the Tomcat/webapps/file directory. Note that the file directory here is an empty Web engineering deployment folder, and if you are only creating a new empty folder for storing files, you cannot access the files in them by linking . The
refers to how storage files are organized, to store various files , in order not to have too many files under a single folder, to build a folder structure with a depth of 4 to the bottom 16 of the hash value of the file name. In principle, you can create 2^16 subfolders to store files in a saturated scenario. The method code to build the file storage path based on the file name is as follows:

/**
     * According to the hash algorithm, determine the storage directory
     * @param filename
     * @return
    /private string GetPath (string filename) {
        try{
            //Gets the hashcode value of the filename, takes the binary 16 bits, the folder depth is 4
            int hashcode = Filename.hashcode ();
            String Dir_suffix = "/" + (Hashcode & 0xf) + "/" + (Hashcode & 0xf0) >> 4) + "/" + (Hashcode & 0xf00) >> 8 + "/" + ((Hashcode & 0xf000) >>);
            Construct a new save directory
            String dir = basepath + dir_suffix;
            File can either represent files or represent directory file file
            = new file (dir);
            If the directory does not exist if
            (!file.exists ()) {
                ///Create directory
                file.mkdirs ();
            }
            return dir;
        } catch (Exception e) {
            e.printstacktrace ();
            return basepath+ "/error";
        }

    

Because the FileUpload plug-in reads the Web file to obtain a imputstream, here, pass in the input stream of the Imputstream and store the file under the subfolder that was built in the previous step:

/**
     * Save File
     * @return return Access link
    /public string Save (string filename, string ext, string operator, Inputstre AM in) throws ioexception{
        fileoutputstream fos = null;
        try{
            String Path = this.getpath (filename);
            FOS = new FileOutputStream (path+ "/+filename+".) +ext);
            byte [] buffer = new byte[1024];
            int length = 0;
            while (length = in.read (buffer)) >0) {
                fos.write (buffer,0,length);
            }
            return path+ "/" +filename+ "." +ext;
        } catch (Exception e) {
            e.printstacktrace ();
            return ERROR;
        } Finally {
            if (null!= in) {
                in.close ();
            }
            if (null!= fos) {
                fos.close ();}}}
    

At the same time, we need to provide access links for files stored on the server. In the following method, it is particularly efficient to calculate the access path of a file by file name , rather than traversing it, according to the storage rules.

/**
     * Returns a file link based on the filename and its extension
     * @param filename
     * @param ext
     * @return/public
    String Getfileuri (String filename,string ext) {
        int hashcode = Filename.hashcode ();
        String Dir_suffix = "/" + (Hashcode & 0xf) + "/" + (Hashcode & 0xf0) >> 4) + "/" + (Hashcode & 0xf00) >> 8 + "/" + ((Hashcode & 0xf000) >>);
        String Realpath =  this.getpath (filename) + "/" +filename+ "." +ext;
        File File = new file (Realpath);
        if (file.exists ()) {
            String domain = systemutil.getproperty ("domain");
            Return domain.substring (0,domain.lastindexof ("/")) +/file "+dir_suffix+"/"+filename+". +ext;
        } else return NONE;
    

This method of building a storage path based on the filename and calculating the external access path requires a strict set of file naming rules for the system . Alternatively, developers can record file names and their corresponding files in different data tables in the database, and of course, by comparison, follow common naming rules, which are more concise and efficient.
In addition, in the Web controller layer, use the FileUpload plug-in to obtain the front-end upload file form each input control information code as follows:

    @RequestMapping (value = "/file") public void file (HttpServletRequest request,httpservletresponse response) throws
        ioexception{Response.setcontenttype ("Application/json;charset=utf-8"); try{///Use Apache File Upload component to process file upload steps://1, create a diskfileitemfactory factory diskfileitemfactory facto
            ry = new Diskfileitemfactory ();
            Sets the size of the factory's buffer, and when the uploaded file size exceeds the buffer size, a temporary file is generated to be stored in the specified temporary directory. Factory.setsizethreshold (1024*100)//Set buffer size of 100KB, if unspecified, then the size of the buffer defaults to the 10KB/*//settings The Save directory of temporary files generated when uploading FA Ctory.setrepository (tmpfile); *//2, create a file upload parser servletfileupload upload = new Servletfileupload (f
            Actory); Monitor File Upload Progress Upload.setprogresslistener (new Progresslistener () {public void update long PBYTESRE AD, long pcontentlength, int arg2) {System.out.println ("File size: + Pcontentlength +", currently processed: "+ pbytes
                Read);
     }
            });       Solve the upload file name of Chinese garbled upload.setheaderencoding ("UTF-8"); 3, to determine whether the data submitted is uploaded form data if (!
            Servletfileupload.ismultipartcontent (Request)) {//Get data return in the traditional way;
            //Set the maximum size of a single file to upload, is currently set to 1024*1024 Byte, that is, 1MB Upload.setfilesizemax (1024*1024*10);
            Set the maximum number of uploaded files, maximum = The maximum size of multiple files uploaded at the same time, currently set to 10MB Upload.setsizemax (1024*1024*30); 4, using the Servletfileupload parser to parse the upload data, the result returned is a list<fileitem> set, each fileitem corresponding to a form of the input items LIST&LT;FILEITEM&G T
            List = Upload.parserequest (request);
                    for (Fileitem item:list) {//If Fileitem encapsulates the data for a normal entry (Item.isformfield ()) {
                    String name = Item.getfieldname ();
                    Solve the Chinese garbled problem of the data of the normal input item String value = item.getstring ("UTF-8");
                    Value = new String (value.getbytes ("iso8859-1"), "UTF-8"); SysteM.OUT.PRINTLN (name + "=" + value);
                    }else{//If the Fileitem is encapsulated in the upload file//Get uploaded file name, String filename = Item.getname ();
                    SYSTEM.OUT.PRINTLN (filename);
                    if (Filename==null | | Filename.trim (). Equals ("")) {continue;
                    //Note: Different browsers submit the file name is not the same, some browsers submit the filename is a path, such as: C:\a\b\1.txt, and some just simple file name, such as: 1.txt
                    Process the path portion of the file name of the uploaded file that is fetched, leaving only the filename part filename = filename.substring (filename.lastindexof ("\") +1); Get upload file extension String fileextname = filename.substring (Filename.lastindexof (".")
                    +1);
                    filename = filename.substring (0,filename.lastindexof ("."));
                    If you need to limit the file type of upload, you can use the file extension to determine whether the file type uploaded is legitimate System.out.println ("uploaded file extension is:" +fileextname);
 Save file FileManager FileManager = new FileManager ();                   if (FileManager.ERROR.equals (Filemanager.save (Filename,fileextname, "song", Item.getinputstream ())) {
                    Response.getwriter (). Write (Jsonutil.statusresponse (1, "Upload file failed", null)); }else response.getwriter (). Write (Jsonutil.statusresponse (0, "Upload file succeeded", Filemanager.getfileuri (filename,fileextname
                )));
            }}catch (Fileuploadbase.filesizelimitexceededexception e) {e.printstacktrace (); Response.getwriter (). Write (Jsonutil.statusresponse (1, "Single file exceeds maximum value ...)
        ", null));
            }catch (fileuploadbase.sizelimitexceededexception e) {e.printstacktrace (); Response.getwriter (). Write (Jsonutil.statusresponse (1, "The total size of the uploaded file exceeds the maximum value of the limit ...)."
        ", null));
            }catch (Exception e) {e.printstacktrace (); Response.getwriter (). Write (Jsonutil.statusresponse (1, "Other exception, upload failed ...")
        ", null));
    } return; }

The corresponding front-end test page code is as follows:

<body>
    <form action= "file" enctype= "Multipart/form-data"
          method= "post" >
        upload User: <input Type= "text" name= "username" ><br/>
        upload file: <input type= "file" Name= "File2" ><br/>
        < Input type= "Submit" value= "Submission" >
    </form>
</body>

The use of FileUpload plug-ins see the above code, specific reference to other online information or related manuals.
After this set, we found that the basic principle of the Distributed file system built up by FASTDFS+SOLR is similar to this, Fastdfs also uses a multi-level folder structure to store files, using SOLR to search for the corresponding files based on specific keywords, rather than searching for complicated file names directly. In this system, the realization of these two characteristics has been embodied. The difference is that FASTDFS provides better data synchronization and disaster response measures, while implementing file server and application server separate, improve the application server responsiveness, it is a digression.
Finally attach a reference link: http://www.cnblogs.com/xdp-gacl/p/4200090.html

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.