Upload e download de anexos, download de anexos, o poço do salto de página do front-end

Uploads e downloads adicionais não foram escritos por eles mesmos no projeto, eles são todos métodos prontos no framework que são chamados diretamente, então toda vez que encontro o framework do projeto não fornece métodos, me sinto tímido, aqui está um registro do que escrevi nos métodos de upload e download do anexo do projeto e os pits encontrados na parte anterior do download;

Atualizando arquivos

O que é fornecido aqui é uma interface, e o upload é executado de forma assíncrona no parágrafo anterior;

A forma de escrever a interface do nosso projeto é um pouco estranha, que não é a mesma que costumamos usar;

O componente de upload de anexo do layui foi usado no parágrafo anterior, que é mais conveniente de escrever;

    /**
     * 附件上传  单文件上传
     * @param request
     * @param response
     * @param
     */
    @RequestMapping(value = "uploadFile", method = RequestMethod.POST)
    public void uploadFile(HttpServletRequest request, HttpServletResponse response){
      {
        Result result = new Result();
        String json = "";
        Claims b = JWTUtil.parseJWT(request.getParameter("token"), ConfigLoader.baseSecurity);
        String accountName = (String) b.get("accountName");
        Accounts account = accountServicesImpl.getEntityBySql("select * from accounts where account_name = '" + accountName + "' and del_flag = 0", null, Accounts.class);
        User user = accountServicesImpl.getUserByAccount(account.getId());
        File file = null;
        try{
//            MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//            MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile multipartFilefile = multipartRequest.getFile("file");

            String filename = "";
            Long size = 0l;
//            MultipartFile multipartFilefile=null;
//            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
//            for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
//                multipartFilefile = entry.getValue();
                filename = multipartFilefile.getOriginalFilename();
                size = multipartFilefile.getSize();
//            }

            // 从数据字典中获取上传路径
            String upconfigPath = "";
            List<CategoryAttributes> leiMuAtt = new ArrayList<CategoryAttributes>();
            leiMuAtt = ConfCache.attributeConfMap.get("Path_Upload");
            if (leiMuAtt != null && leiMuAtt.size() > 0) {
                for (CategoryAttributes tr : leiMuAtt) {
                    CategoryAttributes c = (CategoryAttributes) tr;
                    if (c.getCategoryAttributesName().equals("上传公共路径")) {
                        upconfigPath = c.getCategoryAttributesValue();
                    }
                }
            }
//            String downconfigPath = upconfigPath.substring(upconfigPath.lastIndexOf("/") + 1);
            // 从数据字典中获取下载路径
//             String downconfigPath = "";
//             List<CategoryAttributes> leiMuAttt=new ArrayList<CategoryAttributes>();
//             leiMuAttt=ConfCache.attributeConfMap.get("Path_Download");
//             if(leiMuAtt!=null && leiMuAttt.size()>0){
//                 for (CategoryAttributes tr : leiMuAttt) {
//                     CategoryAttributes c = (CategoryAttributes)tr;
//                     downconfigPath=c.getCategoryAttributesValue();
//                     break;
//                 }
//             }
            // 获取日期时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String date = sdf.format(new Date());
            SimpleDateFormat sdft = new SimpleDateFormat("HHmmssSSS");
            String timeValue = sdft.format(new Date());
            // 上传到服务器的路径(数据字典上传配置+“/attachment/”附件文件夹+日期)
            String dir = "";

            dir = upconfigPath + "/taskfiles/" + date + "/";
//            downconfigPath = downconfigPath + "/taskfiles";

            File directory = new File(dir);
            // 目录不存在,创建目录
            if (!directory.exists()) {
                directory.mkdir();
            }
            // 原文件信息
            System.out.println(filename);

            try {
                filename = java.net.URLDecoder.decode(filename, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            System.out.println(filename);
            String oldfilename = filename.substring(filename.lastIndexOf("\\") + 1);
            String sourcename = oldfilename.substring(0, oldfilename.lastIndexOf(".")); // 文件名
            String ofileType = oldfilename.substring(oldfilename.lastIndexOf(".") + 1); // 文件后缀
            Long ofileSize = size;
            // 新路径(dir配置路径+时间戳.格式后缀)
            String newfile = dir + timeValue + "." + ofileType;
            file = new File(newfile);
            Attachment attachment = new Attachment();// 记录上传的信息
            try {
                if (!file.exists()) {
//                    Accounts account = (Accounts) ss.getAttribute("login_user");
                    attachment.setFileName(sourcename);
                    attachment.setDir(dir); // 下载时的相对路径
                    attachment.setFileSize(ofileSize);
                    attachment.setPhysicalName(timeValue + "");
                    attachment.setCreateTime(new Date());
                    attachment.setCreateUserId(account.getId());
                    // attachment.setAttachedTable(attachedTable);
                    attachment.setStatus(0);
                    attachment.setFileType(0);
                    // attachment.setRecordId(recordId);
                    attachment.setExt(ofileType);
                    attachment.setUploadPath(dir + timeValue + "." + ofileType);
                    attachmentServicesImpl.save(attachment);
                }
//                FileUtils.copyFile((File) files.get(0), file);// 上传 (复制文件)
                FileUtils.copyInputStreamToFile(multipartFilefile.getInputStream(),file);
            } catch (IOException e1) {
                e1.printStackTrace();
                throw new RuntimeException("文件上传失败!");
            }
            StringBuffer sb = new StringBuffer();
            sb.append("{");
            sb.append("\"code\":");
            sb.append(0 + ",");
            sb.append("\"msg\":");
            sb.append("\"上传成功!\",");
            sb.append("\"data\":");
            sb.append(JsonUtil.object2json(attachment));
            sb.append("}");
            json = sb.toString();
        }catch(Exception e){
            StringBuffer sb = new StringBuffer();
            sb.append("{");
            sb.append("\"code\":");
            sb.append(1 + ",");
            sb.append("\"msg\":");
            sb.append("\"上传失败!\",");
            sb.append("}");
            json = sb.toString();
        }
        this.print(json,response);
    }

A dificuldade está em como obter as informações do anexo do HttpServletRequest, que é MultipartFile. No início, foi utilizado o seguinte método

MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> files = multipartRequest.getFiles("files");

Mas esse método relatará um erro, informando que não pode ser convertido diretamente em MultipartHttpServletRequest, portanto, é substituído pela conversão do método superior, portanto, após a alteração, ainda não funciona e informa que o número em multipartRequest.getFiles ( "arquivos") é 0, o que significa que não há anexo, então use o seguinte método:

MultipartFile multipartFilefile=null;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
                multipartFilefile = entry.getValue();
                filename = multipartFilefile.getOriginalFilename();
                size = multipartFilefile.getSize();
            }

O caminho de upload é obtido diretamente do dicionário de dados;

Observação: os dois acima são métodos para fazer upload de vários arquivos, que foram modificados posteriormente, e o código no código é apenas para fazer upload de um único arquivo;

Uma classe de ferramenta FileUtils no pacote org.apache.commons.io é usada aqui. Existem muitas maneiras de manipular arquivos, que podem ser encontrados na Internet, mas não os listarei aqui;

O caminho de upload obtido do dicionário de dados aqui é / u06 / upload, então o caminho para a biblioteca depois que o arquivo é carregado também é este; além disso, e /u06/upload/date/filename.houzhui também é armazenado no banco de dados , e é baixado diretamente durante o download Eu escolhi este campo. Depois que o arquivo foi carregado com sucesso, ele foi finalmente carregado para a pasta / u06 / upload no mesmo nível da minha área de trabalho do projeto;

baixar anexo

Primeiro cole o código do controlador de fundo:

 /**
     * 附件下载
     * @param request
     * @param response
     * @param
     */
    @RequestMapping(value = "downloadFile")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response, String id){
        Result result = new Result();
        try{
            Base base = new Attachment();
            base.setId(id);
            String ids = request.getParameter("id");
            Attachment attachment = (Attachment) attachmentServicesImpl.getBean(base);
            String fileName = attachment.getFileName() + "." + attachment.getExt();
//            String dir = attachment.getDir();
            String path = attachment.getUploadPath();
            File sourceFile = new File(path);
            if (!sourceFile.exists()) {  throw new Exception("您下载的资源已不存在");  }
            BufferedInputStream in = null;
            ServletOutputStream out = null;
            try {
//              fileName = URLEncoder.encode(fileName, "UTF-8"); //解决下载文件名乱码
                response.reset();
                response.setCharacterEncoding("UTF-8");
//              response.setContentType("application/octet-stream");
                response.setContentType("application/force-download");
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                in = new BufferedInputStream(new FileInputStream(sourceFile));
                out = response.getOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception(fileName + " 下载出错,若有问题请与管理员联系");
            } finally {
                out.close();
                in.close();
            }
            result.setSuccess(true);
            result.setMessage("下载成功");
        }catch(Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("下载失败!"+e.getMessage());
        }
//        this.print(result.toString(),response);
    }

Vamos falar sobre os pits encontrados durante o download. Ao fazer o download, cliquei na tag <a> e, em seguida, acionei um ajax para chamar o download em segundo plano, mas esta página não solicitou nenhum aviso de download e nenhum erro foi relatado, mas havia eram arquivos na resposta. O conteúdo, eu verifiquei na Internet e descobri que o download do anexo não pode ser feito com ajax. Parece que ajax retorna o resultado do tipo de caractere, e o navegador não consegue analisar o anexo na resposta , por isso devo mudar o método. Li o método de outras pessoas. O método é útil para window.href.location e também é útil para usar o atributo de download na tag a. Eu também tentei este atributo. O download não é o arquivo original, mas um arquivo vazio chamado download e, em seguida, escreva o plano de fundo diretamente no atributo href. Se o endereço for mapeado, a página salta e não há download de anexo; por fim, o método de envio de dados de formulário é usado para solicitar, então a página não pule, e o anexo pode ser baixado;

Cole o código anterior;

<div class="layui-upload-list">
            <table class="layui-table">
                <thead>
                <tr><th>文件名</th>
                    <th>大小</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr></thead>
                <tbody id="demoList"></tbody>
            </table>
        </div>
 $("#demoList").append('<tr>' +
                                                    '<td><a href="#">'+data.list[i].fileName+'.'+data.list[i].ext+'</a></td>' +
                                                    '<td>'+((data.list[i].fileSize)/1014).toFixed(1)+'kb</td>' +
                                                    '<td><span style="color: #5FB878;">上传成功</span></td>' +
                                                    '<td>' +
                                                        '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'+
                                                        '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete-exist">删除</button>' +
                                                    '</td>' +
                                                    '<td class="layui-hide">'+data.list[i].id+'</td>' +
                                                    '</tr>')
 $("#demoList").find("a").on('click',function (e) {
                                        var p_tr = $(this).parent().parent();
                                        //删除附件数组内的附件id
                                        var tds = p_tr.children();
                                        //找到该附件的主键
                                        var id = tds.eq(4).text();
                                        var $eleForm = $("<form method='get'></form>");
                                        $eleForm.attr("action","/CenterChainTaskController/downloadFile");
                                        $(document.body).append($eleForm);
                                        $eleForm.append('<input type="text" name="id" value="'+id+'">')
                                        //提交表单,实现下载
                                        $eleForm.submit();
                                    })

 

Acho que você gosta

Origin blog.csdn.net/tonglei111/article/details/101039307
Recomendado
Clasificación