当前位置: 代码网 > it编程>编程语言>Asp.net > C#实现文件上传和接收功能

C#实现文件上传和接收功能

2025年08月04日 Asp.net 我要评论
前言web应用开发中,文件上传是一个常见且重要的功能。它不仅涉及到前端用户界面的设计,还涉及到后端服务器如何高效、安全地处理上传的数据。本文将详细介绍一种基于asp.net web api的服务端解决

前言

web应用开发中,文件上传是一个常见且重要的功能。它不仅涉及到前端用户界面的设计,还涉及到后端服务器如何高效、安全地处理上传的数据。

本文将详细介绍一种基于asp.net web api的服务端解决方案以及两种不同的客户端实现方法,帮助开发者更好地理解和实现文件上传功能。

文件上传的核心实现

一、效果展示

通过以下截图可以直观地看到整个文件上传过程的效果:

postman测试

服务端接收

上传成功

二、服务端代码

服务端采用asp.net web api来处理文件上传请求,以下是核心代码片段:

using system;
using system.io;
using system.web;
using system.web.http;

namespace mes.controllers
{
    public class filecontroller : apicontroller
    {
        [httppost]
        public string uploadfile()
        {
            string result = string.empty;
            try
            {
                // 核心部分 文件
                string filename = httpcontext.current.request.files[0].filename;
                stream stream = httpcontext.current.request.files[0].inputstream;

                // 参数
                var forms = httpcontext.current.request.form;
                foreach (var item in forms)
                {
                    string val = forms[item.tostring()];
                }
                // 保存路径
                string uploadfolder = "f:\\图片";
                string savepath = system.io.path.combine(uploadfolder, filename);
                filestream fswrite = new filestream(savepath, filemode.create);

                byte[] bytes = new byte[1024 * 4];
                int total = 0;
                int size = 0;
                do
                {
                    // 注意第二个参数是在buffer中的偏移量,不是在文件中的偏移量
                    size = stream.read(bytes, 0, bytes.length);
                    fswrite.write(bytes, 0, size);
                    total += size;
                }
                while (size > 0);

                fswrite.close();
                result = "true";
            }
            catch (exception ex)
            {
                result = ex.message;
            }
            return result;
        }
    }
}

三、客户端代码

客户端提供了两种方式来上传文件,分别是通过表单(multipart/form-data)的方式一和方式二。

方式一

public string postfile(string url, dictionary<string, object> dics, string filepath)
{
    // 返回结果
    string result = string.empty;
    try
    {
        multipartformdatacontent form = new multipartformdatacontent();
        using (httpclient client = new httpclient())
        {
            mediatypewithqualityheadervalue temp = new mediatypewithqualityheadervalue("application/json") { charset = "utf-8" };
            client.defaultrequestheaders.accept.add(temp);//设定要响应的数据格式

            // 参数
            foreach (var keyvaluepair in dics)
            {
                form.add(new stringcontent(keyvaluepair.value.tostring()), keyvaluepair.key);
            }

            // 读取文件
            stream filestream = new filestream(filepath, filemode.open, fileaccess.read);
            var filename = path.getfilename(filepath);

            // 设定文件类型表单项,使用streamcontent存放文件流
            form.add(new streamcontent(filestream), "file", filename);

            task<httpresponsemessage> task = client.postasync(url, form);
            task.wait(); // 等待异步操作完成
            httpresponsemessage response = task.result;
            response.ensuresuccessstatuscode(); // 确保响应状态码表示成功

            string responsebody = task.result.content.readasstringasync().result;
            console.writeline(responsebody);
            result = responsebody;
        }
        return result;
    }
    catch (exception ex)
    {
        throw new exception(ex.message);
    }
}

方式二

public string postfile(string url, dictionary<string, object> dics, string filepath)
{
    // 返回结果
    string result = string.empty;
    try
    {
        multipartformdatacontent form = new multipartformdatacontent();
        using (httpclient client = new httpclient())
        {
            mediatypewithqualityheadervalue temp = new mediatypewithqualityheadervalue("application/json") { charset = "utf-8" };
            client.defaultrequestheaders.accept.add(temp);//设定要响应的数据格式

            // 参数
            foreach (var keyvaluepair in dics)
            {
                form.add(new stringcontent(keyvaluepair.value.tostring()), keyvaluepair.key);
            }

            // 读取文件 读取为字节数据存入
            using (var filestream = new filestream(filepath, filemode.open, fileaccess.read))
            {
                byte[] data = new byte[filestream.length];
                filestream.read(data, 0, data.length);
                filestream.close();

                var filename = path.getfilename(filepath);
                form.add(new bytearraycontent(data), "file", filename);
            }

            task<httpresponsemessage> task = client.postasync(url, form);
            task.wait(); // 等待异步操作完成
            httpresponsemessage response = task.result;
            response.ensuresuccessstatuscode(); // 确保响应状态码表示成功

            string responsebody = task.result.content.readasstringasync().result;
            console.writeline(responsebody);
            result = responsebody;
        }
        return result;
    }
    catch (exception ex)
    {
        throw new exception(ex.message);
    }
}

总结

本文详细介绍了如何利用asp.net web api实现文件上传功能,并提供了两种不同风格的客户端实现方法。通过这种方式,不仅可以有效提高项目的可维护性和灵活性,还能确保文件上传的安全性与效率。

以上就是c#实现文件上传和接收功能的详细内容,更多关于c#文件上传和接收的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com