FastDFS网页下载(前端借用后端)

原创
小哥 3年前 (2022-11-09) 阅读数 39 #大杂烩

Controller:

@ApiOperation(value="通用接口,dfs文件下载,页面直接调用", notes="null")
    @GetMapping(value = "/dfsdownload/{id}")
    public ItsResultDto dfsDownload(HttpServletResponse response, @PathVariable("id") String id) {
        ItsResultDto result = new ItsResultDto();//返回值
        String UserAgent = this.getUserAgent();//浏览器身份,通常msie
        FileDto detildto = BeanMapper.map(fileAS.getDetail(id), FileDto.class);//根据id查询文件信息。不BeanMapper转换,直接使用也可以。这是代码规范,已转换detildto事实上,也是如此。
        if (StringUtils.isEmpty(detildto) || detildto.getIsdeleted().equals(Constant.IS_DELETE)) {
            result.setCode(FileResultCodeEnum.NOTEXISTERROR.getCode());
            result.setMessage(FileResultCodeEnum.NOTEXISTERROR.getMessage());

            return result;
        } else {
            // 获取IP
            InetAddress inetAddress = null;
            try {
                inetAddress = InetAddress.getLocalHost();
                while (StringUtils.isEmpty(inetAddress)) {
                    inetAddress = InetAddress.getLocalHost();
                    System.out.println("tr00000+" + inetAddress);
                }
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            String ip = inetAddress.getHostAddress().toString();
            System.out.println("00000000000+" + ip);
            System.out.println("00000000000+" + ip);
            // int port=request.getServerPort();
            detildto.setPath(ip + ":" + "8083");
            DownloadDto downloaddto = new DownloadDto();
            String fileName = null;
            String filePath = null;
            if (StringUtils.isEmpty(detildto)) {

            } else {
                fileAS.addcount(id);//在数据库中,给出此文件的下载次数。+1的业务
                downloaddto.setFileName(detildto.getFilename());
                downloaddto.setFilePath(detildto.getPath());
                fileName = detildto.getFilename();// +"."+detildto.getData().getType();

                filePath = detildto.getFakepath();//在dfs中文件的路径,例如:group1/M00/00/04/rBAh2lut3hCAGcOfAABuADP3meg336.xls

            }

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/force-download");

            try {
                // fastDFSClient.dfsdownload(response, path, fileName,UserAgent);
                fastDFSClient.downloadFile(response, filePath, fileName, UserAgent);//方法如下,直接胶合FastDFSClient它可以在中使用。我不知道FastDFSClient的,请参见“在此列中生成”。FastDFS的client’一文
                result.setCode(ResultCodeEnum.SUCCESS.getCode());
                result.setMessage(ResultCodeEnum.SUCCESS.getMessage());

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                result.setCode(ResultCodeEnum.FAIL.getCode());
                result.setMessage(ResultCodeEnum.FAIL.getMessage());
            }

            return result;
        }

    }

在FastDFSClient添加以下方法:

/**
     * 下载文件
     * 
     * @param fileId
     *            文件ID(成功上传文件后返回ID)
     * @param outFile
     *            文件下载保存位置
     * @return
     */
    public void downloadFile(HttpServletResponse response, String filePath, String fileName,String UserAgent) throws IOException {

        BufferedInputStream bis = null;
        OutputStream outs = null;// 获取文件输出IO流
        BufferedOutputStream os = null; // 输出流
        // 本地文件位置
        // String local = "D:/downloadtest/test.jpg";
        byte[] buffer = new byte[1024];
        String path=filePath.substring(filePath.indexOf("/")+1,filePath.length());
        String group=filePath.substring(0,filePath.indexOf("/"));
        File targetFile = new File(path);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

            // System.out.println("1111111111+"+fileName.toString());
            // ((HttpServletResponse) response).setHeader("Content-Disposition",
            // "attachment;filename="+new String(fileName.getBytes("utf-8"),"iso-8859-1"));
            //String userAgent = response.getHeader("User-Agent").toLowerCase();  

        //String outpath=dfsPortl+"/"+filePath;

        try {
            if (UserAgent.contains("MSIE") || UserAgent.contains("like Gecko") ) {  
                // win10 ie edge 浏览器 和其他系统ie  
            fileName = URLEncoder.encode(fileName, "UTF-8");  
        } //else {  
                // fe  
           // fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");  
        //}  
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso-8859-1"));
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            //byte[] content = storageClient1.download_file("group1", "M00/00/00/rBCuaV2IeB6AHY6OAAzodRl2Jqw478.jpg");
            byte[] content = storageClient1.download_file(group, path);
            InputStream inputStream = new  ByteArrayInputStream(content);

            try {
                outs = response.getOutputStream();// 获取文件输出IO流
                os = new BufferedOutputStream(outs);
                bis = new BufferedInputStream(inputStream);
                int i;
                while ((i = bis.read(content)) != -1) {
                    os.write(content, 0, i);
                }
                os.flush();
                os.close();
                bis.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                os.flush();
                os.close();
                bis.close();
            }  

            //fis.read();

            //fos = new FileOutputStream(path);

            // fos.read();
            //BufferedOutputStream bos = new BufferedOutputStream(fos);
            //BufferedInputStream bis = new BufferedInputStream(fis);
            //IOUtils.writeChunked(content, fos);

            /*
             * byte[] by = storageClient1.download_file1(fileId); // 将数据写入输出流
             * IOUtils.write(by, new FileOutputStream(local));
             */

            // return 0;
            /*
             * byte[] content = storageClient1.download_file1(filePath); fos =
             * response.getOutputStream(); fis = new FileInputStream(file); bis = new
             * BufferedInputStream(fis); //IOUtils.copy(content,fos); fos.write(content);
             * int i = bis.read(content); while(i != -1){ fos.write(content); i =
             * bis.read(content); } //IOUtils.writeChunked(content, fos);
             */
        } catch (Exception e) {
            e.printStackTrace();
        } /*finally {
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }*/
        // return -1;
    }

以上是所有的核心代码,业务逻辑可以根据自己的需要进行修改。为了便于有人可能与我的业务相似,我在此发布本文的使用。dto:

package com.***.***.file.interfaces.dto;
import java.math.*;
import java.io.*;
import io.swagger.annotations.*;
import java.util.*;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

@ApiModel(description ="")
public class FileDto {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value="", required=false)
    private String fileuid;

    @ApiModelProperty(value="", required=false)
    private String tenantid;

    @ApiModelProperty(value="", required=false)
    private String filename;

    @ApiModelProperty(value="", required=false)
    private String uploaderno;

    @ApiModelProperty(value="", required=false)
    private String uploadername;

    @ApiModelProperty(value="", required=false)
    private Long size;

    @ApiModelProperty(value="", required=false)
    private Integer downloadcount;

    @ApiModelProperty(value="", required=false)
    private String description;

    @ApiModelProperty(value="", required=false)
    private String type;

    @ApiModelProperty(value="", required=false)
    private String path;

    @ApiModelProperty(value="", required=false)
    private String fakepath;

    @ApiModelProperty(value="", required=false)
    private String isauth;

    @ApiModelProperty(value="", required=false)
    private String isdeleted;

    @ApiModelProperty(value="", required=false)
    private String uploadtime;

    @ApiModelProperty(value="", required=false)
    private String remark;

    @ApiModelProperty(value="", required=false)
    private String tagname;

    /**
     * @return String
     */
    public String getFileuid() {
        return fileuid;
    }

    /**
     * @param String
     */
    public void setFileuid(String fileuid) {
        this.fileuid = fileuid;
    }

    /**
     * @return String
     */
    public String getTenantid() {
        return tenantid;
    }

    /**
     * @param String
     */
    public void setTenantid(String tenantid) {
        this.tenantid = tenantid;
    }

    /**
     * @return String
     */
    public String getFilename() {
        return filename;
    }

    /**
     * @param String
     */
    public void setFilename(String filename) {
        this.filename = filename;
    }

    /**
     * @return String
     */
    public String getUploaderno() {
        return uploaderno;
    }

    /**
     * @param String
     */
    public void setUploaderno(String uploaderno) {
        this.uploaderno = uploaderno;
    }

    /**
     * @return String
     */
    public String getUploadername() {
        return uploadername;
    }

    /**
     * @param String
     */
    public void setUploadername(String uploadername) {
        this.uploadername = uploadername;
    }

    /**
     * @return Long
     */
    public Long getSize() {
        return size;
    }

    /**
     * @param Long
     */
    public void setSize(Long size) {
        this.size = size;
    }

    /**
     * @return Integer
     */
    public Integer getDownloadcount() {
        return downloadcount;
    }

    /**
     * @param Integer
     */
    public void setDownloadcount(Integer downloadcount) {
        this.downloadcount = downloadcount;
    }

    /**
     * @return String
     */
    public String getDescription() {
        return description;
    }

    /**
     * @param String
     */
    public void setDescription(String description) {
        this.description = description;
    }

    /**
     * @return String
     */
    public String getType() {
        return type;
    }

    /**
     * @param String
     */
    public void setType(String type) {
        this.type = type;
    }

    /**
     * @return String
     */
    public String getPath() {
        return path;
    }

    /**
     * @param String
     */
    public void setPath(String path) {
        this.path = path;
    }

    /**
     * @return String
     */
    public String getFakepath() {
        return fakepath;
    }

    /**
     * @param String
     */
    public void setFakepath(String fakepath) {
        this.fakepath = fakepath;
    }

    /**
     * @return String
     */
    public String getIsauth() {
        return isauth;
    }

    /**
     * @param String
     */
    public void setIsauth(String isauth) {
        this.isauth = isauth;
    }

    /**
     * @return String
     */
    public String getIsdeleted() {
        return isdeleted;
    }

    /**
     * @param String
     */
    public void setIsdeleted(String isdeleted) {
        this.isdeleted = isdeleted;
    }

    /**
     * @return String
     */
    public String getUploadtime() {
        return uploadtime;
    }

    /**
     * @param String
     */
    public void setUploadtime(String uploadtime) {
        this.uploadtime = uploadtime;
    }

    /**
     * @return String
     */
    public String getRemark() {
        return remark;
    }

    /**
     * @param String
     */
    public void setRemark(String remark) {
        this.remark = remark;
    }

    /**
     * @return String
     */
    public String getTagname() {
        return tagname;
    }

    /**
     * @param String
     */
    public void setTagname(String tagname) {
        this.tagname = tagname;
    }

}

package com.***.***.file.interfaces.dto;

import java.math.*;
import java.io.*;
import io.swagger.annotations.*;
import java.util.*;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

@ApiModel(description ="")
public class DownloadDto {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value="", required=false)
    private String filePath;

    @ApiModelProperty(value="", required=false)
    private String fileName;

    @ApiModelProperty(value="", required=false)
    private byte[] buffer;

    @ApiModelProperty(value="", required=false)
    private File file;

    @ApiModelProperty(value="", required=false)
    private Integer fis;

    /**
     * @return String
     */
    public String getFilePath() {
        return filePath;
    }

    /**
     * @param String
     */
    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    /**
     * @return String
     */
    public String getFileName() {
        return fileName;
    }

    /**
     * @param String
     */
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    /**
     * @return byte[]
     */
    public byte[] getBuffer() {
        return buffer;
    }

    /**
     * @param byte[]
     */
    public void setBuffer(byte[] buffer) {
        this.buffer = buffer;
    }

    /**
     * @return File
     */
    public File getFile() {
        return file;
    }

    /**
     * @param File
     */
    public void setFile(File file) {
        this.file = file;
    }

    /**
     * @return Integer
     */
    public Integer getFis() {
        return fis;
    }

    /**
     * @param Integer
     */
    public void setFis(Integer fis) {
        this.fis = fis;
    }

}
版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除

热门