ant pro 使用upload上传文件

本文介绍如何在使用dva和ant-pro技术栈的项目中实现文件上传功能。遇到的问题包括使用form表单导致的页面跳转、iframe不发起请求等,最终解决方案是通过dispatch发起请求,并以FormData形式传递二进制流。关键步骤包括点击上传、选择文件、手动触发上传和提交额外参数。注意console.log无法正确显示文件对象,需直接在接口中传递参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目前公司中有写到导入文件的功能模块, 目前使用的技术栈是react 但是在前家公司使用的请求是用 axios 然后自己封装一个post get请求这种, 本次是直接使用ant-pro的盒子, 所以使用的是dva , 请求方式是通过dispatch来发起的, 那么该怎么发起请求和传递参数
一开始也使用了form表单来提交上传文件 但是碰到各种问题, 比如请求以后会跳转页面 , 使用iframe禁止跳转页面以后 他又不发起请求了 等等一系列问题.

上传功能:

  1. 点击上传文件
    在这里插入图片描述
    在这里插入图片描述

<Upload {...props}>
 <Button type="primary">
   上传文件
 </Button>
</Upload>
  1. 选择文件
    在这里插入图片描述

  2. 选择文件以后 并没有直接上传 , 可以自己手动点击上传按钮再上传
    在这里插入图片描述

const props = {
     onRemove: file => {
       this.setState(state => {
         const index = state.fileList.indexOf(file);
         const newFileList = state.fileList.slice();
         newFileList.splice(index, 1);
         return {
           fileList: newFileList,
         };
       });
     },
     beforeUpload: file => {
       this.setState(state => ({
         fileList: [...state.fileList, file],
       }));

       return false;
     },
     fileList,
   };
  1. 点击提交, 提交文件和需要传到 后台的参数
    在这里插入图片描述
    顺便说一句你上传的一定是这样形式的二进制流, 还有你console.log打印importFile一定是个空对象, 别想着打印了, 直接接口传递参数 , 看看 参数格式是不是这种二进制流.

如果显示的是[Object onject]
就取里面的一层
const formData = new FormData();

Ant Design Pro 是一个开箱即用的企业级中后台前端/设计解决方案,提供了众多的组件和模板,方便开发者快速搭建中后台应用。 如果你想在Ant Design Pro中实现文件上传功能,可以使用Ant Design Pro自带的Upload组件。具体步骤如下: 1. 在你的项目中引入Ant Design Pro组件库。可以参考官方文档:https://pro.ant.design/docs/getting-started-cn。 2. 在你的代码中使用Upload组件。示例代码如下: ```jsx import { Upload, message } from 'antd'; import { InboxOutlined } from '@ant-design/icons'; const { Dragger } = Upload; const props = { name: 'file', multiple: true, action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76', onChange(info) { const { status } = info.file; if (status !== 'uploading') { console.log(info.file, info.fileList); } if (status === 'done') { message.success(`${info.file.name} file uploaded successfully.`); } else if (status === 'error') { message.error(`${info.file.name} file upload failed.`); } }, onDrop(e) { console.log('Dropped files', e.dataTransfer.files); }, }; <Dragger {...props}> <p className="ant-upload-drag-icon"> <InboxOutlined /> </p> <p className="ant-upload-text">Click or drag file to this area to upload</p> <p className="ant-upload-hint"> Support for a single or bulk upload. Strictly prohibit from uploading company data or other band files </p> </Dragger> ``` 在以上代码中,我们引入了Upload、message和InboxOutlined组件。其中,UploadAnt Design Pro自带的上传组件,message可以用来弹出提示框,InboxOutlined是一个Ant Design Pro自带的图标组件。 我们使用Dragger组件包裹Upload组件,来实现文件拖拽上传的功能。我们在props中设置了上传文件的相关属性,包括上传接口、上传状态的回调函数等。最后,我们将Dragger组件渲染到页面上,来展示上传组件。 希望以上代码对你有所帮助!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值