文件上传到oss上以及下载

<template>
    <!-- 批量渠道变更 -->
    <div>
        <div style="margin-bottom: 10px; display: flex;">
            <Download name="下载模板" type="Url" url="https://file.wonder-link.net/%E6%89%B9%E9%87%8F%E6%B8%A0%E9%81%93%E5%8F%98%E6%9B%B4.xlsx">
                <dev-button type="primary">下载模板</dev-button>
            </Download>
            <el-upload
                :auto-upload="false"
                :on-change="(val: any) => {beforeUpload(val)}"
                :show-file-list="false"
            >
                <el-button type="primary">批量导入</el-button>
            </el-upload>
        </div>
        <div style="padding-bottom: 30px;">
            <el-table
                v-loading="pageLoading"
                :data="tableData" 
                style="width: 100%"
                border
                :header-cell-style="{ background: '#eff3f6', textAlign: 'center' }"
            >
                <el-table-column prop="batchNo" label="批次号" />
                <el-table-column label="文件名称">
                    <template #default="scope">
                        {{ scope.row.fileName || '-' }}
                    </template>
                </el-table-column>
                <el-table-column label="处理状态">
                    <template #default="scope">
                        {{ scope.row.batchStatusDesc || '-' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作人">
                    <template #default="scope">
                        {{ scope.row.createName || '-' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作时间">
                    <template #default="scope">
                        {{ scope.row.createTime || '-' }}
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="160" align="center">
                    <template #default="scope">
                        <dev-button type="primary" @click="() => getFileUrl(scope.row)" link>下载</dev-button>
                        <dev-button v-if="scope.row.batchStatus == 'TO_PROCESS'" link type="primary" @click="passThrough(scope.row, 'pass')">通过</dev-button>
                        <dev-button v-if="scope.row.batchStatus == 'TO_PROCESS'" link type="primary" @click="passThrough(scope.row, 'refuse')">拒绝</dev-button>
                    </template>
                </el-table-column>
            </el-table>
            <br>
            <div style="float: right;">
                <el-pagination 
                    v-model:current-page="params.pageNo"
                    v-model:page-size="params.pageSize"
                    :page-sizes="[10, 20, 30, 40]"
                    background 
                    layout="sizes, prev, pager, next" 
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </div>
        <ExportButton ref="exportButtonRef" :api="exportApi" :show-button="false" />
    </div>
</template>
<script setup lang='ts'>
import { reactive, ref, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import OSS from 'ali-oss';
import {getOssConfig} from '@/api/noticeSettings/upLoadOss';
import {page_list, audit, download_detail, batch_change } from "@/api/operateMent/ChannelChanges";
import Download from '@/components/Download/index.vue';
import ExportButton from '@/components/ExportButton/index.vue';

const exportApi = download_detail;
const pageLoading = ref(false);
const total = ref(0);
const tableData = ref([]);
let params: any = reactive({
    batchNo: '',
    pageNo: 1,
    pageSize: 10,
});
const exportButtonRef = ref();
// 初始化
const init = () => {
    pageLoading.value = true;
    page_list(params).then((res: any) => {
        pageLoading.value = false;
        tableData.value = res.list;
        total.value = Number(res.total || 0)
    }).catch(() => {
        pageLoading.value = false;
    })
};
const passThrough = (row: any, type: string) => {
    ElMessageBox.confirm(
        `是否确认${type == 'pass' ? '通过' : '拒绝'}吗?`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        audit({batchNo: row.batchNo, audit: type == 'pass' ? 1 : 0, }).then(() => {
            ElMessage.success('操作成功');
            init();
        });
    });
};
const getFileUrl = (item: any) => {
    exportButtonRef.value.passiveExport({batchNo: item.batchNo});
};
onMounted(() => {
    init();
});
const handleSizeChange = (val: number) => {
    params.pageSize = val;
    init();
};
const handleCurrentChange = (val: number) => {
    params.pageNo = val;
    init();
};
const uploadFilledData = ref<any>({});
const client = ref();// oss信息
const beforeUpload = (file: any) => {
    const rawFile = file.raw;
    uploadFilledData.value = rawFile;
    getOssConfig().then((res: any) => {
        client.value = new OSS({
            region: res.region,
            accessKeyId: res.accessKeyId,
            accessKeySecret: res.accessKeySecret,
            stsToken: res.securityToken,
            bucket: res.bucket// 填写Bucket名称。
        });
        nextTick(() => {
            startUploading();
        });
        return true;
    }).catch(()=>{
        window.$message.error('获取oss信息失败');
        return false;
    });
};
const uploadResults = ref<any>({});// 上传结果
// 获取文件名称后缀
const getFileName = (fileName: string) => {
    const arr = fileName.split('.');
    return arr[arr.length - 1];
};
// 去除文件后缀
const removeSuffix = (fileName: string) => {
    const arr = fileName.split('.');
    return arr[0];
};
const startUploading = async () => {
    try {
        // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
        // 您可以通过自定义文件名(例如exampleobject.txt)或文件完整路径(例如exampledir/exampleobject.txt)的形式实现将数据上传到当前Bucket或Bucket中的指定目录。
        // data对象可以自定义为file对象、Blob数据或者OSS Buffer。
        const suffix = getFileName(uploadFilledData.value.name); // 文件后缀
        const fileName = removeSuffix(uploadFilledData.value.name) + new Date().getTime() + '.' + suffix;
        const result = await client.value.put(
            fileName,
            uploadFilledData.value,
        );
        uploadResults.value = result;
        let obj = {
            fileName: result.name,
            filePath: result.url,
        }
        batch_change(obj).then(() => {
            window.$message.success('上传成功');
            init();
        }).catch(() => {
            window.$message.error('上传失败');
        })
    } catch (e) {
        window.$message.error('上传失败');
    }
};
</script>
  • 24
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是Java实现File文件上传OSS的示例代码: ``` import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.PutObjectRequest; import com.aliyun.oss.model.PutObjectResult; import java.io.File; public class OSSFileUploader { // 阿里云 OSS 信息 private static final String ENDPOINT = "your-endpoint"; private static final String ACCESS_KEY_ID = "your-access-key-id"; private static final String ACCESS_KEY_SECRET = "your-access-key-secret"; private static final String BUCKET_NAME = "your-bucket-name"; // 上传文件到 OSS public static void uploadFile(File file) { // 创建 OSS 客户端 OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET); // 创建 PutObjectRequest 对象 PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, file.getName(), file); // 上传文件到 OSS PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest); // 打印上传结果 System.out.println("File uploaded: " + putObjectResult.getETag()); // 关闭 OSS 客户端 ossClient.shutdown(); } public static void main(String[] args) { // 上传本地文件 File file = new File("your-local-file-path"); uploadFile(file); } } ``` 需要将上述代码中的 `your-endpoint`、`your-access-key-id`、`your-access-key-secret` 和 `your-bucket-name` 替换为自己的阿里云 OSS 相关信息,将 `your-local-file-path` 替换为要上传的本地文件路径。执行 `uploadFile()` 方法即可将本地文件上传OSS

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值