jquery-uploadfile use (asynchronous multi-file upload)

demand

In the end you can not refresh the page in the page word document upload multiple size limit of the case, save the file and return to the path, and you can delete a file by mistake upload.

ready

    • Download the plugin
    • The plug-in relies jquery1.9.1 version (the other is not clear)
      * introduction of style files and js files in jsp page
</script><link href="css/uploadfile.css" rel="stylesheet">  
<script src="js/jquery1.9.1/jquery.min.js"></script>
<script src="js/jquery.uploadfile.min.js"></script>

Write jsp page

  • Forms
<form id="newsform" method="post" action="control/news/add.action"  enctype="multipart/form-data" >    
        <input type="hidden" name="columnId" value="${columnId }">
        <input type="hidden" name="state" id="state" >
        <div id="fileuploader" > Post attachments </ div> 
    </ form>  
    • js function
      I was directly written in the jsp page
<Script> 
$ (Document) .ready (function () { 

    $ ( " #fileuploader " ) .uploadFile ({ 
        URL: " Control / News / upload.action " , // background processing method 
        fileName: " myfile " ,    // name of the file, here is the variable name, the original file name is not just background received parameters 
        dragDrop: to true ,   // can cancel 
        abortStr: " cancel " , 
        sequential: to true ,   // order to upload 
        sequentialCount: 1 ,   // press order to upload
        autosubmit: " false " ,   // canceled automatically upload 
        acceptFiles: " the Application / vnd.openxmlformats-officedocument.wordprocessingml.document, the Application / msword " , // limit the upload file format 
        extErrorStr: " upload file format is wrong " , 
        maxFileCount: 10 ,        // upload the file number 
        maxFileSize: 1024 * 1024 , // size limits 1M 
        sizeErrorStr: " Upload file can not be greater than 1M " , 
        dragDropStr: "<span> <b> drag attachments thereto </ B> </ span> " , 
        showFileCounter: to false , 
        the returnType: " JSON " ,   // return data format JSON 
        the onSuccess: function (Files, Data, XHR, PD)   // upload successful event, data is returned as background data 
        {
             // upload files returned id dynamically added form, for returning to the background when the form is submitted. 
            var newsform = $ ( " #newsform " );
            IF (the data. == Status . 1 ) {
                 for ( var I = 0 ; I <data.data.length; I ++ ) {
                     var inputNode='<input type="hidden" id="'+data.data[i].fileId+'" name="fileIds" value="'+data.data[i].fileId+'" >';
                    newsform.append(inputNode);
                }
            }else{
                alert("上传失败");
            } 
        },
        showDelete: true,//删除按钮
        statusBarWidth:600,
        dragdropWidth:600,
            delete button method of execution//
        deleteCallback: function (data, pd) {
             var fileId=data.data[0].fileId;
             $.post("control/news/deleteFile.action", {fileId:fileId},
                    function (resp,textStatus, jqXHR) {
                        alert("delete ok");
                        //alert(textSatus);
              }); 
            //删除input标签
            $("#"+fileId).remove();
            pd.statusbar.hide(); //You choice.
        }
    });
});
</script> 

 

/**
     * 上传新闻附件
     * @return
     * {
     *   "status":1,
     *    "message":"ok",
     *    "data":[
     *     {"fileId":"20164225567979423"}
     *     {"fileId":"20164225567979423"}
     *     {"fileId":"20164225567979423"}
     *     ...
     *    ]
     * }
     */
    @RequestMapping(value="upload", method=RequestMethod.POST)
    public String uploadFile(MultipartHttpServletRequest request,Model model,String name,String testName){

       MyStatus status = new MyStatus();
       JSONObject json= new JSONObject();

       Iterator<String> iterator = request.getFileNames();
       //遍历所有上传文件
       JSONArray jsonArray = new JSONArray();
        while (iterator.hasNext()) {
                String fileName = iterator.next();
                MultipartFile multipartFile = request.getFile(fileName);
                String originName=multipartFile.getOriginalFilename();

                //保存文件相对路径:files/
                String relativedir= SiteUtils.getRelativeSavePath("news.file" );
                 // Save the file name 
                String saveFileName = WebUtils.getFileSaveName (originName);
                 the try {
                     // Save the file 
                    BaseForm.saveFile (relativedir, saveFileName, MultipartFile);
                     // configuration file entity 
                    NewsFile newsFile = new new NewsFile (); 
                    newsFile. setOriginName (originName); 
                    newsFile.setSaveName (saveFileName); 
                    newsFile.setSavePath (relativedir + saveFileName); 
                    newsFile.setExt (WebUtils.getExtFromFilename (saveFileName));
                    newsFile.setSize(multipartFile.getSize());
                    newsFileService.save(newsFile);
                    //构造json
                    JSONObject fileJson = new JSONObject();
                    fileJson.put("fileId", newsFile.getId());
                    jsonArray.add(fileJson);
                } catch (Exception e) {
                    e.printStackTrace();
                    status.setStatus(0);
                    status.setMessage(e.getMessage());
                    break;
                }
        }
        //返回json数据
        json.put("status", status.getStatus());
        json.put("message", status.getMessage());
        json.put("data", jsonArray);
        model.addAttribute("json", json.toString());
        return SiteUtils.getPage("json");
    }

Write back method to delete files

/**
     * 删除附件记录
     * @param fileId
     * @return
     */
    @RequestMapping(value="deleteFile")
    public String deleteNewsFile(String fileId,Model model){

        MyStatus status = new MyStatus();
        try {
            if( BaseForm.validateStr(fileId)){
                newsFileService.delete(fileId);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            status.setStatus(0);
            status.setMessage(e.getMessage());
        }
        JSONObject json = JSONObject.fromObject(status);
        model.addAttribute("json", json.toString());
        return SiteUtils.getPage("json");
    }  

I believe many people have problems and bottlenecks in the fourth year of front-end or mid-time will always be, as some time learning not get no sense of direction or a boring person to learn how to solve a problem do not know, I am finishing up like some of the information I'd like to discuss the article and learn together with more experienced Daniel, then welcome to join my group study exchange 907 694 362

Guess you like

Origin www.cnblogs.com/xsd1/p/11963651.html