第32章 uView多文件上传

1 WebApi.Controllers.ProductController

using Microsoft.AspNetCore.Mvc;

using Microsoft.Net.Http.Headers;

using WebApi.Data;

using WebApi.Domain.Catalog;

namespace WebApi.Controllers

{

    [ApiController]

    [Route("[controller]/[action]")]

    public class ProductController : ControllerBase

    {

        private readonly EFCoreContext _eFCoreContext;

        private readonly IHttpContextAccessor _httpContextAccessor;

        private readonly IWebHostEnvironment _webHostEnvironment;

        public ProductController(EFCoreContext eFCoreContext,

         IHttpContextAccessor httpContextAccessor,

         IWebHostEnvironment webHostEnvironment)

        {

            _eFCoreContext = eFCoreContext;

            _httpContextAccessor = httpContextAccessor;

            _webHostEnvironment = webHostEnvironment;

        }

        private string GetAbsoluteAvatarUrl(string virtualAvatarUrl)

        {

            string absoluteAvatarUrl = string.Empty;

            var hostHeader = string.Empty;

            if (_httpContextAccessor.HttpContext.Request.IsHttps)

            {

                hostHeader = "https://" + _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.Host];

            }

            else

            {

                hostHeader = "http://" + _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.Host];

            }

            if (string.IsNullOrEmpty(virtualAvatarUrl))

            {

                absoluteAvatarUrl = hostHeader + "/images/Product/Default.jpg";

            }

            else

            {

                absoluteAvatarUrl = hostHeader + virtualAvatarUrl;

            }

            return absoluteAvatarUrl;

        }

        #region CURD

        [HttpGet]

        public List<Product> ProductList()

        {

            var productList = _eFCoreContext.ProductDbSet.ToList();

            for (int i = 0; i < productList.Count; i++)

            {

                var pictureList = _eFCoreContext.PictureDbSet.Where(p=>p.ProductId.Equals(productList[i].Id)).ToList();

                for (int j = 0; j < pictureList.Count; j++)

                {

                    pictureList[j].VirtualPath = GetAbsoluteAvatarUrl(pictureList[j].VirtualPath);

                }

                productList[i].PictureCollection = pictureList;

            }

            return productList;

        }

        /// <param name="id">1个指定产品的长整型值。</param>

        /// <param name="formFileCollection">多个指定的上传文件实例的集合。</param>

        /// <summary>

        /// 【上传多个文件--无需权限】

        /// </summary>

        /// <remarks>

        /// 摘要:

        ///     把多个指定的上传文件从客户端上传到服务器端的指定目录中。

        /// 说明(elmentUI Upload组件)

        ///   1、如果使用头属性字典传递customerId参数实例,则不用使用“[FromForm]”标记,

        /// URL为:this.actionRequestUrl = "https://localhost:7239/Customer/PostAvatarStream?customerId=" + this.formUser.id;

        ///   2、如果使用“:data/:form-data”传递customerId参数实例,则必须使用“[FromForm]”标记,否则customerId参数实例会一直为:0

        /// URL为:this.actionRequestUrl = "https://localhost:7239/Customer/PostAvatarStream"

        /// 注意:

        ///   formFileCollection参数实例在多文件上传中1次只包含1个指定的上传文件实例。

        /// </remarks>

        /// <returns>

        /// 返回:

        ///     多个指定的上传文件上传操作后的状态信息。

        /// </returns>

        [HttpPost]

        public bool PostAvatarStream([FromForm] long id, IFormFileCollection formFileCollection)

        {

            if (formFileCollection != null)

            {

                foreach (IFormFile formFile in formFileCollection)

                {

                    if (formFile.Length > 0)

                    {

                        string _avatarDirectory = _webHostEnvironment.WebRootPath + @"\images\Product\"+id+ @"\";

                        string _filePath = string.Empty;

                     

                         string _filename = Guid.NewGuid().ToString() + Path.GetExtension(formFile.FileName);

                        _filePath = _avatarDirectory + _filename;

                        using FileStream fileStream = new FileStream(_filePath, FileMode.Create);

                        formFile.CopyTo(fileStream);

                        Picture picture = new Picture();

                        picture.ProductId = id;

                        picture.VirtualPath= $"/images/Product/{id}/{_filename}";

                        _eFCoreContext.PictureDbSet.Add(picture);

                        _eFCoreContext.SaveChanges();

                    }

                }

                return true;

            }

            return false;

        }

        #endregion

    }

}

2 pages\Product\ProductList\ProductList.vue

<template>

    <view class="content">

        <u-table>

            <u-tr>

                <u-td width="100rpx"> 编号</u-td>

                <u-td width="700rpx">名称</u-td>

                <u-td width="320rpx">封面</u-td>

                <u-td>图集</u-td>

            </u-tr>

            <u-tr v-for="(item, index) in list" :key="index">

                <u-td width="100rpx">{{ item.id }}</u-td>

                <u-td width="700rpx">{{ item.name }}</u-td>

                <u-td width="320rpx" v-for="(itemCoverImage, indexCoverImage) in item.pictureCollection"

                    :key="indexCoverImage">

                    <view v-if="itemCoverImage.coverImage">

                        <!-- <u-image width="280rpx" height="280rpx" :src="itemCoverImage.virtualPath"></u-image> -->

                        <!-- 如果使用“u-upload ”组件本身显示上传预览图片,则必须设置:deletable="true" -->

                        <u-upload

                            :action="actionRequestUrl"

                            :auto-upload="true"

                            name="formFileCollection"

                            :maxCount="10"

                            :form-data="{id: item.id}"

                            :file-list="[{url:itemCoverImage.virtualPath}]"

                            :show-progress="false"

                            :multiple="true"

                            :deletable="true"

                            :show-upload-list="true"

                            >

                        </u-upload>

                    </view>

                </u-td>

                <u-td v-for="(itemPicture, indexPicture) in item.pictureCollection" :key="indexPicture+'CoverImage'">

                    <u-image width="100rpx" height="100rpx" :src="itemPicture.virtualPath"></u-image>

                </u-td>

            </u-tr>

        </u-table>

    </view>

</template>

<script>

    import axios from 'axios';

    export default {

        data() {

            return {

                list: [],

                //文件上传--上传文件所需要调用的指定的后端控制器行为方法。

                actionRequestUrl: 'https://localhost:7144/Product/PostAvatarStream',

                //文件上传--需要或已经被上传的文件。

                filelist: [],

            }

        },

        async onLoad() {

            await this.ProductAll();

        },

        methods: {

            async ProductAll() {

                this.list = await (await axios.get('https://localhost:7144/Product/ProductList')).data;

                console.log(".NeCore--HTTPS: localhost:7144--可用域名示例:", this.list);

            },

        }

    }

</script>

<style lang="scss" scoped>

    .content {

        display: flex;

        flex-direction: column;

        align-items: center;

        justify-content: center;

        padding: 40rpx;

    }

    .logo {

        height: 200rpx;

        width: 200rpx;

        margin-top: 100rpx;

        margin-left: auto;

        margin-right: auto;

        margin-bottom: 50rpx;

    }

    .text-area {

        display: flex;

        justify-content: center;

    }

    .title {

        font-size: 28rpx;

        color: $u-content-color;

    }

    .button-demo {

        margin-top: 80rpx;

    }

    .link-demo {

        margin-top: 80rpx;

    }

</style>

对以上功能更为具体实现和注释见:230722_032WebApi(uView多文件上传)

230722_006uView_default(uView多文件上传)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
.cs 界面代码 using System; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; public partial class _Default : System.Web.UI.Page { string name="b";//根据需要给上传的图片命名 int minsize=1;//上传文件的最低大小,单位kb int maxsize=1000;//上传文件的最大大小,单位kb protected void Page_Load(object sender, EventArgs e) { } protected void upload_Click(object sender, EventArgs e) { string fileName, fileExtension, FullName; if (UpImage.PostedFile != null) { if (UpImage.PostedFile.ContentLength != 0 && UpImage.PostedFile.ContentLength <= (1024 * maxsize) && UpImage.PostedFile.ContentLength >= (1024 * minsize)) { fileName = System.IO.Path.GetFileName(UpImage.PostedFile.FileName); fileExtension = System.IO.Path.GetExtension(fileName); if (IsExtension(fileExtension)) { try { FullName = name; CreateDir("upLoadImg"); FullName = DateTime.Now.ToString("yyyyMM") + "/" + FullName; UpImage.PostedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath(@"UpFiles/upLoadImg/") + FullName); } catch (Exception ex) { Response.Write("<script language=javascript>alert('" + ex.Message + "');</script>"); } } else { Response.Write("<script language=javascript>alert('上传的文件格式不对,请上传指定的文件格式!');</script>"); } } else { Response.Write("<script language=javascript>alert('没有上传文件,或者文件太大!请重新上传!');</script>"); } } }
要使用uView上传文件,您需要先引入uView的Upload组件。在您的vue文件中,可以使用以下代码引入Upload组件: ```javascript <template> <upload-file></upload-file> </template> <script> import { uploadFile } from "uview-ui"; export default { components: { "upload-file": uploadFile, }, }; </script> ``` 然后,在您的template标签中,使用以下代码来渲染Upload组件: ```javascript <template> <upload-file :upload-url="uploadUrl" :file-size-limit="fileSizeLimit" :file-type-limit="fileTypeLimit" :multiple="multiple" @success="onUploadSuccess" @fail="onUploadFail" > <view slot="default">上传文件</view> </upload-file> </template> ``` 在这个例子中,我们将Upload组件命名为upload-file,并且传入了一些属性。其中,upload-url表示上传文件的地址,file-size-limit表示文件大小限制,file-type-limit表示文件类型限制,multiple表示是否允许上传多个文件。同时,我们也定义了onUploadSuccess和onUploadFail事件处理函数,用于处理上传成功和上传失败的情况。 最后,在您的script标签中,定义onUploadSuccess和onUploadFail事件处理函数,用于处理上传成功和上传失败的情况: ```javascript <script> import { uploadFile } from "uview-ui"; export default { components: { "upload-file": uploadFile, }, data: { uploadUrl: "http://your-upload-url.com", fileSizeLimit: 10 * 1024 * 1024, // 10MB fileTypeLimit: ["jpg", "jpeg", "png", "gif"], multiple: true, }, methods: { onUploadSuccess(response) { console.log("Upload success: ", response); }, onUploadFail(error) { console.log("Upload fail: ", error); }, }, }; </script> ``` 在这个例子中,我们只是简单地打印了上传成功和上传失败的结果。您可以根据您的实际需求,将这些事件处理函数改成您需要的逻辑。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值