java file upload

These days inadvertently turn their old code to do a development in this note-taking

File Upload:

Front-end using file upload component layui

springboot frame background use


 

The front page code:

html:

<button type="button" class="layui-btn" id="test1"><i class="layui-icon">&#xe67c;</i>上传图片</button>

js:

  // Common Image Upload 
          var uploadInst = upload.render ({ 
            elem: '# test1' 
            , URL: '/ the uploadFile / the uploadFile' 
            , Data: { 
                filetype: ". 1" 
            } 
              , size: 0 
            , before: function (obj) {
               / * // local file read-ahead example, does not support IE8 
              obj.preview (function (index, file, the Result) { 
                $ ( '# demo1') attr ( 'src', the Result);. // picture link (base64) 
              }); * / 
            } 
            , DONE: function (RES) {
               //If the upload has failed 
              IF (res.code> 0 ) {
                 return layer.msg ( 'failed to upload' ); 
              } the else  IF (res.code === 0) { // successfully uploaded 

                  zuo.department.image = res.fileid; 
                  zuo.department.imageurl = res.fileurl; 

                  
              } 
              
            } 
            , error: function () {
               // presentation failed state, and to achieve a retransmission 
              var demoText = $ ( '# demoText' ); 
              demoText.html ('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
              demoText.find('.demo-reload').on('click', function(){
                uploadInst.upload();
              });
            }
          });

Background java code:

 

Application.java added

 / **   
     * Configuration File Upload   
     * @return   
     * /   
    @Bean   
    public MultipartConfigElement multipartConfigElement () {   
        MultipartConfigFactory Factory = new new MultipartConfigFactory ();  
         // a maximum single file   
        factory.setMaxFileSize ( "10240KB"); // KB, MB   
        // / The total size of the data set uploads   
        factory.setMaxRequestSize ( "102400KB" );  
         return factory.createMultipartConfig ();   
    }  

 

External constants:

/ ** 
     * file upload address (pc) home folder (default) 
     * / 
    Private String Folder = "C: //" ; 
    
    / ** 
     * file upload address (pc) folder (default) 
     * / 
    Private String pcfile = "the Upload / pcfiles /" ; 
    
    / ** 
     * = 1 image filename filetype 
     * / 
    Private String Image = "Image" ; 
    
    / ** 
     * documentation = 2 filetype 
     * / 
    Private String = Office "Office" ; 
    
    / ** 
     * video 3 = filetype 
     * / 
    Private String Video = "Video" ; 
    
    / ** 
     * = 4 seed filetype 
     * / 
    Private String bt = "bt" ; 
    
    / **
     * 音乐 filetype=5
     */
    private String misic = "misic";
    
    /**
     * 其他 filetype=6
     */
    private String other = "other";

 

Main methods:

    / ** * 
     * Upload a single file (normal file upload) 
     * js can be directly transferred to this method, but also can be a tool interface 
     * synchronization method 
     * @param File 
     * @param file specified by fileurl memory address: there are with, if any, use the default 
     * @ param filetype (1: picture 2: document 3: video, 4: seed 5: Music, 6: other) 
     * @return  
     * sUCCESS success / failure 
     * msg prompt content 
     * fileid file the above mentioned id 
     * file specified by fileurl access to the file url 
     * / 
    @ RequestMapping ( "/ uploadFile" ) 
    @ResponseBody 
    public  the synchronized the Map <String, Object>uploadFilex (a MultipartFile File, fileurl String, String filetype, the HttpServletRequest Request, the HttpServletResponse Response) { 

        / ** 
         * Method main block 
         * / 
        the Map <String, Object> = Result new new the HashMap <String, Object> (); 
        the HttpSession the session = Request. the getSession ();
         the try { 
            
            
            / ** 
             * this person 
             * / 
            the User User = (the User) session.getAttribute ( "the USER" ); 
            
            / ** 
             * here path (customize) 
             * / 
            String filePath = "" ;
             / ** 
             * picture access address 
             * /
            URL String = "" ; 
            
            / ** 
             * not pass type (automatic determination) 
             * / 
            IF (filetype == null ) { 
                
                the InputStream INPUT = file.getInputStream (); 
                
                / ** 
                 * determines the type of file 
                 * / 
                Integer T = FileTypeJudge .isFileType ( 
                                 FileTypeJudge.getType (INPUT)); 
                filetype = t.toString (); 
            } 
            / ** 
             * stored in different folders of different file 
             * / 
            IF (fileurl == null || fileurl.equals ( ""  )) {
                filePath=folder+pcfile;
                url = pcfile;
                if(filetype.equals("1")){//图片
                    filePath +=this.image;
                    url +=this.image;
                }else if(filetype.equals("2")){//文档
                    filePath +=this.office;
                    url +=this.office;
                }else if(filetype.equals("3")){//视频
                    filePath +=this.video;
                    url +=this.video;
                }else if(filetype.equals("4")){//种子
                    filePath +=this.bt;
                    url +=this.bt;
                }else if(filetype.equals("5")){//音乐
                    filePath +=this.misic;
                    url +=this.misic;
                }else{//其他
                    + = filePath the this .OTHER; 
                    URL + = the this .OTHER; 
                } 
            } the else { 
                filePath = fileurl; 
            } 
            / ** 
             * Get the file path of the uploaded image 
             * / 
            File picFile = new new File (filePath);
             / ** 
             * Analyzing file folder exists, if it does not exist create 
             * / 
            IF (! picFile.isDirectory ()) { 
                picFile.mkdirs (); // mkdir to create a single-folder; mkdirs create multiple folders 
            }
             / **
             * Need to return the file name 
             * / 
            String OriginalFilename = null ;
             / ** 
             * filename prefix 
             * / 
            String prefix = file.getOriginalFilename () substring (0, file.getOriginalFilename () lastIndexOf (.. "." ));
             / ** 
             * file extension 
             * / 
            String suffix . = file.getOriginalFilename () substring (. "." file.getOriginalFilename () lastIndexOf ( ), 
                    file.getOriginalFilename () length ().); 
            
            Long size = file.getSize () ; 
            
            / * 
             * processing size 
             * / 
            String filesize= getPrintSize(size);
            
            
            /**
             * Stored in the database (default =. 1 isdel) 
             * / 
            WcFile wcFile = new new WcFile (); 
            wcFile.setFilename (prefix); 
            wcFile.setFiletype (filetype); 
            wcFile.setFileformat (suffix); 
            wcFile.setFilesize (filesize); 
            wcFile. setCreatetime ( new new a Date ()); 
            wcFile.setCreateperson (user.getId () + "" ); 
            wcFile.setUpdatetime ( new new a Date ()); 
            wcFile.setUpdateperson (user.getId () + "" ); 
            wcFile.setIsdel ( "1"); // before the file did not upload, delete default
            wcFile.setStatus ( "0"); // not upload 
            wcFileService.insert (wcFile); // warehousing, returns to the above mentioned id 
            int the above mentioned id = wcFile.getId (); 
            
            / ** 
             * generate a new file name (UUID added + _ + file id) to avoid conflicts 
             * / 
            String uuid = UUID.randomUUID () toString () replaceAll ( "-", ".". ); 
            OriginalFilename = uuid + "_" + the above mentioned id + suffix;
             / ** 
             * do not have to deal with here IO streams closed issue because FileUtils.copyInputStreamToFile () internal method will automatically be used to turn off the flow of IO 
             * here you can also use MultipartFile.transferTo (file dest) method Spring provides file upload 
             * / 
            file.transferTo ( new newFile (filePath, OriginalFilename));
              / ** 
              * FileUtils.copyInputStreamToFile (myfile.getInputStream (), new new 
              * File (filePath, OriginalFilename)); 
              * Image Compression 
              * * / 
            
            / ** 
             * After a successful upload (updates the corresponding data file ) * 
             / 
            url = url + "/" + OriginalFilename; 
            wcFile.setFileurl (url); // stored in the file address 
            wcFile.setIsdel ( "0"); // display 
            wcFile.setStatus ( "1"); // uploaded successfully 
            wcFileService.updateByPrimaryKey (wcFile); 
            
            / ** 
             * rich text picture package feedback url (http://localhost:8080/upload/test.html)
             */
            String url2=request.getScheme()+"://"+ request.getServerName()+":"+request.getLocalPort();
            Map<String, Object> result2 = new HashMap<String, Object>();
            result2.put("src",url2+"/"+url);
            
            
            result.put("code", 0);//layui 识别成功
            result.put("SUCCESS", true);
            result.put("msg", "上传成功");
            result.put("data", result2);
            result.put("fileid", wcFile.getId());
            result.put("fileurl", url);//访问地址;如:upload/pcfiles/xxxx.xx
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("SUCCESS", false);
            result.put("msg", "上传失败");
            return result;
        }
    }

 

Wherein the file format is determined automatically added portion

See blog post: the Java file upload, automatically determine the file type

Part of which database operations, the need to modify for their own projects related operations

 

Reproduced in: https: //www.cnblogs.com/zktww/p/11016697.html

Guess you like

Origin blog.csdn.net/weixin_34290000/article/details/92864523