vue2.0 使用element-ui里的upload组件实现多图上传。采用FORMDATA的方式上传

本文介绍如何使用 Element-UI 的 Upload 组件实现自定义多图上传功能。通过 HTML 和 JavaScript 代码展示了文件数量限制、预览图片、自定义上传逻辑等关键步骤。

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

原文地址:https://blog.youkuaiyun.com/a12541254/article/details/79187130

这边博文主要介绍的是使用element-ui的upload上传组件实现自定义多图上传的方式。

element-ui的upload上传组件,如果是多图上传,实际上在请求中为单个文件上传,只是提交方法中自循环,直至上传文件列表为空为止。

不多说上代码:

HTML:

[html]  view plain  copy
  1. <el-upload class="upload-demo" action="http://localhost:80" :limit='5' :auto-upload="false" :on-exceed='uploadOverrun' ref="upload" :http-request='submitUpload' :on-change='changeUpload'>  
  2.       <el-button size="small" type="primary">点击上传</el-button>  
  3.       <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>  
  4. </el-upload>  
[html]  view plain  copy
  1. <el-button @click = 'submitAssess'>提交到服务器</el-button>  

JS:

[javascript]  view plain  copy
  1. uploadOverrun: function() {  
  2.                 this.$message({  
  3.                     type: 'error',  
  4.                     message: '上传文件个数超出限制!最多上传5张图片!'  
  5.                 });  
  6.             },  
  7.             changeUpload: function(file, fileList) {//预览图片  
  8.                 this.fileList = fileList;  
  9.                 this.$nextTick(  
  10.                     () => {  
  11.                         let upload_list_li = document.getElementsByClassName('el-upload-list')[0].children;  
  12.                         for (let i = 0; i < upload_list_li.length; i++) {  
  13.                             let li_a = upload_list_li[i].children[0];  
  14.                             let imgElement = document.createElement("img");  
  15.                             imgElement.setAttribute('src', fileList[i].url);  
  16.                             imgElement.setAttribute('style'"max-width:50%;padding-left:25%");  
  17.                             if (li_a.lastElementChild.nodeName !== 'IMG') {  
  18.                                 li_a.appendChild(imgElement);  
  19.                             }  
  20.                         }  
  21.                     })  
  22.             },  
  23.             submitUpload: function(content) {//自定义的上传图片的方法  
  24.                 //1. 创建formData 利用AXIOS传递  
  25.                 let formData = new FormData;  
  26.                 formData.append('file', content.file);  
  27.                 let config = {  
  28.                     'Content-Type''multipart/form-data'  
  29.                 }  
  30.                 let var_this = this;  
  31.                 axios.post('/Index/upload', formData, config)  
  32.                     .then(function(response) {  
  33.                         if (!response.data.success) {  
  34.                             var_this.$message({  
  35.                                 message: response.data.message,  
  36.                                 type: 'error'  
  37.                             });  
  38.                         }  
  39.                     })  
  40.                     .catch(function(error) {  
  41.                         console.log(error);  
  42.                     })  
  43.             },  
  44. submitAssess: function() {this.$refs.upload.submit(); //调用submit方法  
  45.              //其他业务代码。  
  46.          }  
php

[php]  view plain  copy
  1. public function upload(){  
  2.         //上传文件  
  3.         if(!empty($_FILES)) {  
  4.             if(!empty($_SESSION)){  
  5.                 //拼接路径  
  6.                 $filePathArr = explode('/'$_SERVER['SCRIPT_FILENAME']);  
  7.                 array_pop($filePathArr);  
  8.                 $filePath = implode('/'$filePathArr);  
  9.                 $filePath .= '/static/upload/';  
  10.                 if(!is_dir($filePath)){ //创建文件夹  
  11.                     mkdir($filePath);  
  12.                 }  
  13.                 $filePath .= Session::get('user').'-->'.md5(time()).$_FILES['file']['name'];  
  14.                 if(move_uploaded_file($_FILES["file"]["tmp_name"],$filePath)){  
  15.                     $filePath = str_replace($_SERVER['CONTEXT_DOCUMENT_ROOT'],"",$filePath);  
  16.                     //其他业务代码.我在制作此处时,我先将图片存入数据库  
  17.                       
  18.                 }else{  
  19.                     $data = returnData(false,'对不起,操作失败!请稍候再试!');  
  20.                 }  
  21.             }else{  
  22.                $data = returnData(false,'请登录后再试!');  
  23.             }  
  24.             echo json_encode($data);  
  25.         }  
  26.   
  27.     }  
### Vue3 中使用 Element UI 的 `el-upload` 组件与 Django 后端配合实现手动上传片 #### 前端设置 为了在前端集成 `el-upload` 和 `el-form` 来完成文件上传操作,需确保安装并引入了必要的库: ```bash npm install element-plus axios vue@next ``` 创建表单组件时,定义一个用于存储待上传像数据的对象。此对象作为双向绑定的目标,以便于收集用户输入的信息。 ```javascript // src/components/UploadImageForm.vue <template> <el-form :model="form"> <!-- 上传 --> <el-form-item label="上传片" prop="image"> <el-upload ref="upload" action="" list-type="picture-card" :auto-upload="false" :on-change="handleChange" :file-list="form.imageList" > <i class="el-icon-plus"></i> </el-upload> </el-form-item> <el-button type="primary" @click="submitForm">提交</el-button> </el-form> </template> <script setup> import { reactive } from 'vue'; import axios from 'axios'; const form = reactive({ imageList: [] }); function handleChange(file, fileList) { const formData = new FormData(); fileList.forEach(f => { formData.append('images', f.raw); }); } async function submitForm() { try { let formData = new FormData(); // 将所有选中的文件加入到FormData实例中 this.$refs.upload.submit().then((files) => { files.fileList.forEach(function (item) { formData.append("images", item.raw); }); await axios.post('/api/upload/', formData, { headers: {'Content-Type': 'multipart/form-data'} }).catch(error => console.error(error)); alert('上传成功'); }); } catch (error) { console.log(error.message); } } </script> ``` 上述代码片段展示了如何利用 `el-upload` 控件来捕获用户的文件选择动作,并通过自定义事件处理器将这些文件附加到 `FormData` 对象内[^2]。 #### 后端配置 对于Django项目而言,除了常规的应用程序搭建外,还需特别注意媒体资源路径的设定以及视函数的设计以接收来自客户端的数据流。 ##### 设置静态和媒体文件路径 编辑项目的 settings.py 文件,指定媒体文件保存的位置及其URL前缀: ```python # myproject/settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads') ``` 这一步骤明确了服务器上实际存放用户上传资料的具体位置[^1]。 ##### 创建API接口处理上传逻辑 编写专门负责接受HTTP POST请求并将接收到的内容写入磁盘的方法: ```python from rest_framework.views import APIView from rest_framework.response import Response from django.core.files.storage import default_storage class FileUploadAPIView(APIView): def post(self, request): file_obj = request.FILES.getlist('images') saved_files = [] for img in file_obj: path = default_storage.save(img.name, img) saved_files.append(path) return Response({'message': 'Files uploaded successfully.', 'paths': saved_files}) ``` 该类继承自 DRF 提供的基础视基类 `APIView`, 并重写了默认行为以适应特定需求——即解析 multipart/form-data 类型的消息体获取其中携带的一个或个二进制大对象(BLOB),再借助内置工具将其持久化至本地文件系统中去[^4]. 最后记得注册路由映射关系使得外部能够访问新建立的服务端点.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值