java图片上传 和.mp4的文件链接为blob:http://加密的格式

2023-12-25 16:39:17

java图片上传

package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/*
* 通用接口
* */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    /*
    * 上传文件 到阿里云OSS服务器  file和前端参数名保持一致
    * */

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传:{}",file);
        try {
            //原始文件名
            String originalFilename=file.getOriginalFilename();
            //截取原始文件名的后缀  1.jpg
           String extension= originalFilename.substring(originalFilename.lastIndexOf("."));
           //构造新文件名称
            String objectName= UUID.randomUUID().toString()+extension;
            //文件的请求路径
            String filePath= aliOssUtil.upload(file.getBytes(),objectName);
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败:{}",e);
        }
        //定义一个字符串常量
        return Result.error(MessageConstant.UPLOAD_FAILED);

    }


    /*
     * 上传文件 到本地服务器
     * */

    @PostMapping("/uploadben")
    @ApiOperation("文件上传到本地")
    public Result<String> uploadben(MultipartFile file){
        log.info("文件上传到本地:{}",file);
        try {
            //原始文件名
            String originalFilename=file.getOriginalFilename();
            //截取原始文件名的后缀  1.jpg
            String extension= originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName= UUID.randomUUID().toString()+extension;
            log.info("新的文件名:{}",objectName);

            // 确定存储目录
            String projectDir = System.getProperty("user.dir"); //获取当前项目的根目录
            System.out.println(projectDir);
            LocalDate date = LocalDate.now(); // 获取当前日期
            String folderPath="/public/uploads/"+ date.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))+"/"; // 将日期格式化为字符串,比如 "2023/10/23"
            String folderName =projectDir+folderPath;
            File folder = new File(folderName);
            if (!folder.exists()) {
                boolean result = folder.mkdirs(); // 如果文件夹不存在,则创建它,包括任何需要但不存在的父目录
            }
            //文件的请求路径
            file.transferTo(new File(folderName+objectName));
            return Result.success(folderPath+objectName);
        } catch (IOException e) {
            log.error("文件上传失败:{}",e);
        }
        //定义一个字符串常量
        return Result.error(MessageConstant.UPLOAD_FAILED);

    }
    /*
    * 文件下载
    * */
    @GetMapping("/download")
    @ApiOperation("文件下载")
    public void downloadfile(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //加载文件的位置
        File file = new File("D:/ApowerREC/20211124_084339.mp4");
        //获取文件名
        String fileName = file.getName();
        //判断浏览器的类型
        String userAgent = req.getHeader("User-Agent").toLowerCase();
        //如果是火狐浏览器的话,设置浏览器的编码格式
        if (userAgent.indexOf("firefox") != -1) {
            System.out.println("====================火狐浏览器====================");
            resp.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GB2312"), "ISO-8859-1"));
        }
        else {
            System.out.println("====================谷歌浏览器====================");
            resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        }

        //设置response编码
        resp.setCharacterEncoding("UTF-8");
        resp.addHeader("Content-Length", "" + file.length());
        //设置输出文件类型
        resp.setContentType("video/mpeg4");
        FileInputStream fis = null;
        OutputStream os = null;

        try {
            //获取response输出流
            os = resp.getOutputStream();
            fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                // 输出文件
                os.write(buffer,0,len);
            }
        } catch (Exception e) {
            if (null != fis) {
                fis.close();
            }

            if (null != os) {
                os.flush();
                os.close();
            }
        }


    }
    /*
     * 模型文件下载
     * */
    @GetMapping("/downloadglb")
    @ApiOperation("模型文件下载")
    public void downloadfileglb(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //加载文件的位置
        File file = new File("D:/ApowerREC/收费站Draco.glb");
        //获取文件名
        String fileName = file.getName();
        //判断浏览器的类型
        String userAgent = req.getHeader("User-Agent").toLowerCase();
        //如果是火狐浏览器的话,设置浏览器的编码格式
        if (userAgent.indexOf("firefox") != -1) {
            System.out.println("====================火狐浏览器====================");
            resp.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GB2312"), "ISO-8859-1"));
        }
        else {
            System.out.println("====================谷歌浏览器====================");
            resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        }

        //设置response编码
        resp.setCharacterEncoding("UTF-8");
        resp.addHeader("Content-Length", "" + file.length());
        //设置输出文件类型
        resp.setContentType("application/glTF-binary");
        FileInputStream fis = null;
        OutputStream os = null;

        try {
            //获取response输出流
            os = resp.getOutputStream();
            fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                // 输出文件
                os.write(buffer,0,len);
            }
        } catch (Exception e) {
            if (null != fis) {
                fis.close();
            }

            if (null != os) {
                os.flush();
                os.close();
            }
        }


    }


}


vue3前端请求下载地址

<template>
    <div class="p-2">
		 <video :src="videosrc" style="width: 500px;height: 200px;"    controls preload="auto" controlslist="nodownload"></video>
    </div>
</template>
<script setup>
import {ref,onMounted,onBeforeUnmount,reactive,computed } from 'vue'
import  service  from '~/api/apiaxios';
const videosrc=ref(null);
onMounted(async()=>{
    const res2= await service.get(`/admin/common/download`,{responseType: "blob"}).then(data=>{
		console.log(data)
		let url = window.URL.createObjectURL(new Blob([data]))
		console.log(url)
		videosrc.value=url
		// let link = document.createElement("a")
		// link.style.display = "none"
		// link.href = url
		// let filename = (new Date()).getTime() + ".mp4"
		// link.setAttribute("download", filename)
		// document.body.appendChild(link)
		// link.click()
	})
 }) 
 onBeforeUnmount(()=> {
 
 })
 
</script>
<style>

</style>

在这里插入图片描述

文章来源:https://blog.csdn.net/weixin_45086164/article/details/135200574
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。