文件服务器的上传下载接口

简介: 在我们日常开发中,文件服务器是经常用的。本文将介绍如何实现上传下载接口。

image.png

在我们日常开发中,文件服务器是经常用的。本文将介绍如何实现上传下载接口。

1.上传

这里有一个实体 用于存放文件信息,存放路径commonfile在配置文件中配置。

@RestController
public class FileUpload {
    @Value("${commonfile}")
    private String commonfile;
    /**
     * 使用Spring MVC的multipartFile 类作为参数
     *
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    @ArchivesLog(operationName = "上传")
    public Result<FileMessage> uploadMultipartFile(@RequestParam("file") MultipartFile multipartFile) {
        Result<FileMessage> result = new Result<FileMessage>();
        FileMessage fileMessageVO = new FileMessage();
        String fileName = multipartFile.getOriginalFilename();
        try {
            // 获取文件字节数组
            byte[] bytes = multipartFile.getBytes();
            // 文件存储路径(/fileupload1/ 这样会在根目录下创建问价夹)
            File pfile = new File(commonfile);
            // 判断文件夹是否存在
            if (!pfile.exists()) {
                // 不存在时,创建文件夹
                pfile.mkdirs();
            }
            // 创建文件
            File file = new File(pfile, fileName);
            // 写入指定文件夹
            OutputStream out = new FileOutputStream(file);
            out.write(bytes);
            // 组装对象
            fileMessageVO.setFileName(fileName);
            fileMessageVO.setFileRoute(commonfile);
            fileMessageVO.setFileDownloadUri(commonfile + fileName);
            fileMessageVO.setSize(getPrintSize(file.length()));
            fileMessageVO.setFileType(fileName.substring(fileName.lastIndexOf(".") + 1));
            result.setData(fileMessageVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    public static String getPrintSize(long size) {
        // 如果字节数少于1024,则直接以B为单位,否则先除于1024,后3位因太少无意义
        if (size < 1024) {
            return String.valueOf(size) + "B";
        } else {
            size = size / 1024;
        }
        // 如果原字节数除于1024之后,少于1024,则可以直接以KB作为单位
        // 因为还没有到达要使用另一个单位的时候
        // 接下去以此类推
        if (size < 1024) {
            return String.valueOf(size) + "KB";
        } else {
            size = size / 1024;
        }
        if (size < 1024) {
            // 因为如果以MB为单位的话,要保留最后1位小数,
            // 因此,把此数乘以100之后再取余
            size = size * 100;
            return String.valueOf((size / 100)) + "." + String.valueOf((size % 100)) + "MB";
        } else {
            // 否则如果要以GB为单位的,先除于1024再作同样的处理
            size = size * 100 / 1024;
            return String.valueOf((size / 100)) + "." + String.valueOf((size % 100)) + "GB";
        }
    }
}

实体类

public class FileMessage {
    /**
     * 文件名称
     */
    private String fileName;
    /**
     * 文件路径
     */
    private String fileRoute;
    /**
     * 下载地址
     */
    private String fileDownloadUri;
    /**
     * 文件类型
     */
    private String fileType;
    /**
     * 文件大小
     */
    private String size;
}

2.下载

@RestController
public class FileDownload {
    @Value("${commonfile}")
    private String commonfile;
    @GetMapping("/download")
    public String downloadFile(FileMessage fileMessage) throws UnsupportedEncodingException {
        // 获取HttpServletResponse
        HttpServletResponse response =
            ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
        String fileName = fileMessage.getFileName();// 文件名
        if (fileName != null) {
            // 设置文件路径
            File file = new File(commonfile + fileName);
            if (file.exists()) {
                RequestAttributes requsetAttributes = RequestContextHolder.currentRequestAttributes();
                HttpServletRequest request = ((ServletRequestAttributes)requsetAttributes).getRequest();
                // 获得浏览器代理信息
                final String userAgent = request.getHeader("USER-AGENT");
                // 判断浏览器代理并分别设置响应给浏览器的编码格式
                if (StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Trident")) {
                    // IE浏览器
                    fileName = URLEncoder.encode(fileName, "UTF-8");
                } else if (StringUtils.contains(userAgent, "Mozilla")) {
                    // google,火狐浏览器
                    fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
                } else {
                    // 其他浏览器
                    fileName = URLEncoder.encode(fileName, "UTF-8");// 其他浏览器
                }
                // 设置HTTP响应头
                response.reset();
                // 重置 如果不在页面上显示而是下载下来 则放开注释
                // response.setContentType("application/octet-stream");// 告知浏览器下载文件,而不是直接打开,浏览器默认为打开
                // response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");// 下载文件的名称
                try {
                    OutputStream os = response.getOutputStream();
                    // 读取文件
                    InputStream in = new FileInputStream(file);
                    // copy文件
                    IOUtils.copy(in, os);
                    in.close();
                    os.close();
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } 
            }
        }
        return "下载失败";
    }
}


相关文章
|
JSON 监控 API
在线网络PING接口检测服务器连通状态免费API教程
接口盒子提供免费PING检测API,可测试域名或IP的连通性与响应速度,支持指定地域节点,适用于服务器运维和网络监控。
2470 0
|
弹性计算 网络安全
阿里云国际OpenAPI多接口快速管理ECS服务器教程
阿里云国际OpenAPI多接口快速管理ECS服务器教程
|
消息中间件 安全 Linux
服务器(Linux)在线下载activeMQ以及配置打开
服务器(Linux)在线下载activeMQ以及配置打开
429 3
|
C# 图形学 开发者
Unity开发中使用UnityWebRequest从HTTP服务器下载资源。
总之,UnityWebRequest就是游戏开发者手中的万能钓鱼竿,既可以获取文本数据,也能钓上图片资源,甚至是那声音的涟漪。使用UnityWebRequest的时候,你需要精心准备,比如确定URL、配置请求类型和头信息;发起请求;巧妙处理钓获的数据;还需要机智面对网络波澜,处理各种可能出现的错误。按照这样的过程,数据的钓取将会是一次既轻松愉快也效率高效的编程钓鱼之旅。
1007 18
|
Linux
Linux 服务器下载百度网盘文件
本教程指导如何使用 `bypy` 库从百度网盘下载文件。首先通过 `pip install bypy` 安装库,接着运行 `bypy info` 获取登录链接并完成授权,最后将文件置于指定目录并通过 `bypy downdir /Ziya-13b-v1` 命令下载至本地。
2285 1
Linux 服务器下载百度网盘文件
阿里云国际版购买了服务器后如何下载发票?
阿里云国际版购买了服务器后如何下载发票?
|
JavaScript 前端开发
vue配合axios连接express搭建的node服务器接口_简单案例
文章介绍了如何使用Express框架搭建一个简单的Node服务器,并使用Vue结合Axios进行前端开发和接口调用,同时讨论了开发过程中遇到的跨域问题及其解决方案。
539 0
vue配合axios连接express搭建的node服务器接口_简单案例
|
前端开发 JavaScript
【node写接口】 通过node 快速搭建一个服务器、get请求、post请求 小白入门
【node写接口】 通过node 快速搭建一个服务器、get请求、post请求 小白入门
1057 4
软件开发常用之SpringBoot文件下载接口编写(下),Vue+SpringBoot文件上传下载预览,服务器默认上传是1M,可以调节,调节文件上传大小写法,图片预览,如何预览后下次还能看到,预览写法
软件开发常用之SpringBoot文件下载接口编写(下),Vue+SpringBoot文件上传下载预览,服务器默认上传是1M,可以调节,调节文件上传大小写法,图片预览,如何预览后下次还能看到,预览写法
|
数据安全/隐私保护
解决使用SourceTree下载GitLab服务器上的代码每次都需要输入密码问题
解决使用SourceTree下载GitLab服务器上的代码每次都需要输入密码问题
999 2

热门文章

最新文章