Fanwei E9 Form Modeling Query List Batch File Download

Foreword

This code is just a sample code. It can be realized by a simple local test, which may involve the risk of SQL injection. During use, please handle it by yourself and perform encrypted transmission and other operations.

1. System check

1.1, check system settings

Whether the image storage directory and the file storage directory are configured, there is no need to configure.

The screenshot is for reference only, and the actual path is filled in according to the customer's environment.

image-20230524160618942

2. Configuration

2.1, query list code block

Corresponding modeling query list configuration code block

image-20230524160835903

The insertion code is as follows:

Modify modeid, see [View Module ID] for details

Modify fieldName: change to the database field name corresponding to the attachment field of the main modeling table

<script type="text/javascript">
/*
* Please write the JS code below
*/
     function batchDownloadFile() {<!-- -->
        //module ID
        var modeid = "1010";
        //attachment field name
        var fieldName = "xgfj";
        //User check data id format is 1,2,3,4,5
        var ids = ModeList. getCheckedID();
        // non-null check
        if ("" == ids) {<!-- -->
            antd.message.error("Please select the data to be downloaded");
        } else {<!-- -->
            //For performance considerations, only 10 pieces of data can be downloaded each time
            if (ids. split(","). length > 50) {<!-- -->
                antd.message.error("Check up to 50 pieces of data");
            } else {<!-- -->
                //Click to batch download
                var url = "/api/weavernorth/downloads/fileDownload?ids=" + ids + " & amp;modeid=" + modeid + " & amp;fieldName=" + fieldName;
                window.location.href = url;
            }
        }
    }
</script>

<style type="text/css">
/*
* Please edit the CSS below
*/

</style>

2.2, module configuration page extension

image-20230524163157571

image-20230524162508201

**Link target address information:**javascript: batchDownloadFile();

image-20230524163223144

2.3, query list open shortcut button

image-20230524164249856

3. View module ID

Find the module corresponding to the query list, and the id in the foundation is the module ID

image-20230524161254134

4. Backend code implementation

FiledownloadAction.java

package com.engine.web.weaver;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.engine.web.wn.util.FileUtilWn;
import com.engine.web.wn.util.FormmodeUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.system.SystemComInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import java.io.File;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import static com.engine.web.wn.util.FileUtilWn.getRealDoc;

/**
 * @Classname FiledownloadAction
 * @Description TODO
 * @Version 1.0.0
 * @Date 2023/5/24 10:39
 * @Created by
 */

public class FiledownloadAction {<!-- -->
    private static final Logger log = LoggerFactory. getLogger(FiledownloadAction. class);

    @GET
    @Path("/fileDownload")
    @Produces({<!-- -->"application/octet-stream"})
    public Response fileDownload(@Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception {<!-- -->
        SystemComInfo systemComInfo = new SystemComInfo();
        String filesystem = systemComInfo.getFilesystem();
        String ids = request. getParameter("ids");
        String modeid = request. getParameter("modeid");
        String fieldName = request. getParameter("fieldName");
        Map<String, String> modeInfo = FormmodeUtil. getModeInfo(modeid);
        RecordSet rs = new RecordSet();
        String sql = "select " + fieldName + " from " + modeInfo.get("tablename") + " where id in (" + ids + ")";
        log.info("executed sql=" + sql);
        rs. executeQuery(sql);
        String docids = "";

        String zipfilename = System.currentTimeMillis() + "";
        //The path where the system files are restored is also the path of the compressed folder
        String zippath = filesystem + File.separator + "batchfile" + File.separator + zipfilename;
        log.info("beforepath=" + zippath);
        FileUtil.mkdir(zippath);
        while (rs. next()) {<!-- -->
            docids + = Util.null2String(rs.getString(fieldName)) + ",";
        }
        if (docids. endsWith(",")) {<!-- -->
            docids = docids.substring(0, docids.lastIndexOf(","));
        }
        log.info("docids=" + docids);
        if (!"".equals(docids)) {<!-- -->
            List<String> list_imgid = FileUtilWn.getImageFileIdByDocId(docids);
            for (int i = 0; i < list_imgid. size(); i ++ ) {<!-- -->
                getRealDoc(Util. getIntValue(list_imgid. get(i), 0), zippath);
            }
        }
        //folder is not empty
        if (!FileUtil.isDirEmpty(new File(zippath))) {<!-- -->
            File zipFile = ZipUtil.zip(zippath);
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            zipfilename = zipFile.getName().replace(",",",")
                    .replace("?", "?").replace("!", "!")
                    .replace("[", "【").replace("]", "】")
                    .replace("(", "(").replace(")", ")");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipfilename, "UTF-8"));
            FileUtilWn.writeBytes(zipFile, response.getOutputStream());
            //delete target folder
            FileUtil.del(new File(zippath));
            //Delete the compressed package file
            FileUtil.del(zipFile);
        }
        return Response.status(Response.Status.OK).build();
    }

    public static void main(String[] args) {<!-- -->
        String beforepath = "D://123";
        ZipUtil.zip(beforepath);
        FileUtil.del(new File(beforepath));
    }

}

FileUtilWn.java

package com.engine.weaverhb.util;

import weaver.conn.RecordSet;
import weaver.file.ImageFileManager;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname FileUtil
 * @Description TODO
 * @Version 1.0.0
 * @Date 2023/5/24 12:22
 * @Created by
 */
public class FileUtilWn {<!-- -->
    private static Logger log = LoggerFactory. getLogger(FileUtilWn. class);

    public static List<String> getImageFileIdByDocId(String docids) {<!-- -->
        RecordSet rs = new RecordSet();
        List<String> list = new ArrayList<String>();
        String sql = "select imagefileid from DocImageFile dif where docid in (" + docids + ")";
        log.info("sql: " + sql);
        rs. executeQuery(sql);
        while (rs. next()) {<!-- -->
            list.add(rs.getString("imagefileid"));
        }
        log.info("list:" + list);
        return list;
    }

    /**
     * Note that the input is imagefielid, and the obtained one is the full path in the disk (path + file name)
     *
     * @param imageFileId
     * @param unzipPath unzip path
     * @return
     * @throws IOException
     */
    public static String getRealDoc(int imageFileId, String unzipPath) throws IOException {<!-- -->
        String realPath = "";
        ImageFileManager im = new ImageFileManager();
        im.getImageFileInfoById(imageFileId);
        InputStream in = im.getInputStreamById(imageFileId);
        if (in != null) {<!-- -->
            String imageFileName = im.getImageFileName().replaceAll("[\s\\/:\*\?\"<>\ \\|]", " & amp;");
            OutputStream os = null;
            try {<!-- -->
                os = new FileOutputStream(new File(unzipPath + File.separator + imageFileName));
                //file copy
                byte flush[] = new byte[1024];
                int len = 0;
                while (0 <= (len = in. read(flush))) {<!-- -->
                    os.write(flush, 0, len);
                }
                os. flush();
                realPath = unzipPath + imageFileName;
                log.info("realPath=" + realPath);
            } catch (Exception e) {<!-- -->
                e.printStackTrace();
            } finally {<!-- -->
                if (os != null & amp; & amp; in != null) {<!-- -->
                    //Close the attention of the stream, open it first and then close it
                    os. close();
                    in. close();
                }
            }
        } else {<!-- -->
            log.info("Failed to read system files, InputStream is null");
        }
        return realPath;
    }

    /**
     * @param file file
     * @param os output stream
     */
    public static void writeBytes(File file, OutputStream os) {<!-- -->
        FileInputStream fi = null;
        try {<!-- -->
            fi = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fi. read(b)) > 0) {<!-- -->
                os. write(b, 0, length);
            }
        } catch (Exception e) {<!-- -->
            e.printStackTrace();
        } finally {<!-- -->
            if (os != null) {<!-- -->
                try {<!-- -->
                    os. close();
                } catch (IOException e) {<!-- -->
                    e.printStackTrace();
                }
            }
            if (fi != null) {<!-- -->
                try {<!-- -->
                    fi. close();
                } catch (IOException e) {<!-- -->
                    e.printStackTrace();
                }
            }
        }
    }
}

FormmodeUtil.java

package com.engine.weaverhb.util;

import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname FormmodeUtil
 * @Description form modeling tool class
 * @Version 1.0.0
 * @Date 2022/8/25 0025 14:11
 * @Created by
 */
public class FormmodeUtil {<!-- -->
    private Logger log = LoggerFactory. getLogger(FormmodeUtil. class);

    public static Map<String, String> getModeInfo(String modeid) {<!-- -->
        Map<String, String> map = new HashMap<String, String>();
        RecordSet rs = new RecordSet();
        String sql = "select a.formid,b.id,b.tablename from Modeinfo a ,workflow_bill b where a.formid =b.id and a.id=?";
        rs. executeQuery(sql, modeid);
        if (rs. next()) {<!-- -->
            map.put("formid", Util.null2String(rs.getString("formid")));
            map.put("billid", Util.null2String(rs.getString("id")));
            map.put("tablename", Util.null2String(rs.getString("tablename")));
        }
        return map;
    }


}