JS: cargar varios archivos, descargar archivos

Descripción general

Para cargar varios archivos, debe configurar el atributo de entrada como múltiple. No se requieren configuraciones si se carga un solo archivo

Cargar implementación

<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="./jquery.min.js"></script>
</head>

<body>
    <form id="uploadForm" action="" method="post" enctype="multipart/form-data">
        <h2>多文件上传 </h2>
        <table>
            <tr>
                <td>上传文件: <input type="file" name="file[]" id="file" multiple="multiple" /></td>
            </tr>
            <tr>
                <td>
                    <input type="button" value="上传" id="but" />
                </td>
            </tr>
        </table>
    </form>
</body>

</html>
<script>
    //文件上传
    $("#but").click(function () {
      
      
        var formData = new FormData($("#uploadForm")[0]);
        $.ajax({
      
      
            url: '',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (returndata) {
      
      
                alert(returndata);
            },
            error: function (returndata) {
      
      
                alert(returndata);
            }
        });
    })
</script>

Descargar implementación

La descarga de archivos se puede realizar a través de la etiqueta a.

  1. código de interfaz
let url =""
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
document.body.appendChild(link)
link.click()
// 释放URL对象所占资源
window.URL.revokeObjectURL(url)
// 用完即删
document.body.removeChild(link)
  1. código de fondo

Si se cargan varios archivos, el parámetro es una matriz de archivos

/**
     * 获取上传的图片.
     *
     * @return 数据
     */
    @GetMapping(value = "")
    @ResponseBody
    public Result downloadFile(HttpServletResponse response, final HttpServletRequest req) {
    
    
        String title;
        try {
    
    
            title = URLDecoder.decode(req.getParameter("title"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
    
    
            title="压缩包";
        }
        try {
    
    
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(title+".zip", "UTF-8"));
        } catch (UnsupportedEncodingException e) {
    
    
            response.setHeader("Content-Disposition", "attachment;filename=" + "processs.zip");
            e.printStackTrace();
        }
        response.setHeader("Connection", "close");
        response.setHeader("Content-Type", "application/octet-stream");
        String piids = req.getParameter("piids");
        if (StringUtils.isBlank(piids)){
    
    
            return new Result(false,"导出失败:流程piid为空");
        }
        String[] piidArr = StringUtils.split(piids,",");
        try {
    
    
            return new Result(true,integratedQueryService.exportProcessFormInfo(piidArr,response.getOutputStream())) ;
        } catch (IOException e) {
    
    
            return new Result(false,"流程压缩包导出失败,请联系管理员进行解决") ;
        }
    }

//查询文件,把文件输出到zip输出流
public String exportProcessFormInfo(final String[] piidArr, ServletOutputStream outputStream) {
    
    
        try (ZipOutputStream zos = new ZipOutputStream(outputStream)) {
    
    

            if (piidArr.length<=0){
    
    
                return "流程piid为空,不能导出流程压缩包!";
            }
            String processImagePath = processImage.getPath();

            File file1 = new File(processImagePath);

            FileInputStream inputStream;
            try {
    
    
                inputStream = new FileInputStream(file1);
            }catch (FileNotFoundException exception){
    
    
                LOGGER.error("流程截图获取失败,piid:{}",piid);
                continue;
//                            return "流程截图获取失败,piid:"+piid;
            }

            //流程截图的名称
            zos.putNextEntry(new ZipEntry(processImage.getTitle()+".jpg"));
            int len;
            // 读入需要下载的文件的内容,打包到zip文件
            byte[] buffer = new byte[1024];
            while ((len = inputStream.read(buffer)) > 0) {
    
    
                zos.write(buffer, 0, len);
            }
            zos.closeEntry();
            inputStream.close();
              
            attachmentMapper.updateProcessByPiid(piid);

       
        return "流程压缩包导出成功";
    }

Supongo que te gusta

Origin blog.csdn.net/qq_41848006/article/details/128430400
Recomendado
Clasificación