C#(WebService)-(傳輸檔案)

本文介绍了一个基于WebService的文件上传解决方案,包括服务器端的文件创建与追加写入功能实现,以及客户端的文件选择与分块上传流程。通过具体代码示例展示了如何利用WebService进行大文件的稳定传输。

WebService端:



        [WebMethod]
        public bool CreateFile(string fileName)
        {
            bool isCreate = true;
            try
            {
                fileName = Path.Combine(Server.MapPath("File"), Path.GetFileName(fileName));
                /*
                 首先设置上传服务器文件的路径  
                 然后发布web服务 发布的时候要自己建一个自己知道的文件夹
                 "C:\NMGIS_Video" "C:\NMGIS_Video"  fileName = Path.Combine(Server.MapPath("") + @"\Video" + Path.GetFileName(fileName));  
                 */            
                FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                fs.Close();
            }
            catch
            {
                isCreate = false;
            }
            return isCreate;
        }


        [WebMethod]
        public bool Append(string fileName, byte[] buffer)
        {
            bool isAppend = true;
            try
            { 
                fileName = Path.Combine(Server.MapPath("File"), Path.GetFileName(fileName));
                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                fs.Seek(0, SeekOrigin.End);
                fs.Write(buffer, 0, buffer.Length);
                fs.Close();
            }
            catch
            {
                isAppend = false;
            }
            return isAppend;

        }


客戶端:

        private void btnfile_Click(object sender, EventArgs e)
        {
            string file = "";
            string filename = "";
            WebServiceDemoSoapClient MyWebService2 = new WebServiceDemoSoapClient();


            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有文件(*.*)|*.*";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                file = dialog.FileName;
                filename = Path.GetFileName(dialog.FileName);
                fileaddress.Text = file;
            }


            MyWebService2.CreateFile(filename);
            //要上传文件的路径  


            FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            int size = (int)fs.Length;
            int bufferSize = 1024 * 512;
            int count = (int)Math.Ceiling((double)size / (double)bufferSize);
            for (int i = 0; i < count; i++)
            {
                int readSize = bufferSize;
                if (i == count - 1)
                    readSize = size - bufferSize * i;
                byte[] buffer = new byte[readSize];
                fs.Read(buffer, 0, readSize);
                MyWebService2.Append(filename, buffer);


            }




        }



### C# WebService 图片上传与下载实现方法 #### 使用WebService进行图片上传 为了通过C# WebService实现图片上传功能,可以创建一个`WebMethod`来接收客户端发送过来的文件流并保存到指定位置。 ```csharp using System; using System.IO; using System.Web.Services; public class FileService : WebService { [WebMethod(Description = "用于上传图片")] public void UploadImage(byte[] fileData, string fileName) { try { string filePath = HttpContext.Current.Server.MapPath("~/Images/") + fileName; using (FileStream fs = new FileStream(filePath, FileMode.Create)) { fs.Write(fileData, 0, fileData.Length); } } catch (Exception ex) { throw new Exception($"上传失败: {ex.Message}"); } } } ``` 此代码片段定义了一个名为`UploadImage`的方法[^1],它接受两个参数:一个是字节数组形式的图像数据(`fileData`);另一个是要存储的文件(`fileName`)。该函数会尝试将接收到的数据写入服务器上的特定目录下,并处理可能出现的各种异常情况。 #### 使用WebService进行图片下载 对于图片下载,则可以通过返回Base64编码后的字符串或者直接返回二进制数组的方式让前端解析显示或保存下来。 ```csharp [WebMethod(Description = "下载服务器站点文件,传递文件相对路径")] public byte[] DownloadFile(string strFilePath) { string fullPath = HttpContext.Current.Server.MapPath(strFilePath); if (!System.IO.File.Exists(fullPath)) throw new FileNotFoundException("找不到请求的文件"); return System.IO.File.ReadAllBytes(fullPath); } ``` 上述代码展示了如何构建一个简单的下载接口。这里假设传入的是相对于应用根目录的有效路径(例如:“/Images/example.jpg”),接着读取对应物理地址下的文件内容作为响应体的一部分发回给调用者。 #### 客户端调用方式 当涉及到跨页面交互时,通常会选择Ajax异步请求的方式来发起对WebService的操作。下面是一个基于jQuery库的例子: ```javascript // JavaScript部分 - Ajax上传图片至WebService function uploadImage() { var formData = new FormData(); var files = document.getElementById('imageInput').files; for (var i = 0; i < files.length; i++) { formData.append("upload", files[i]); } $.ajax({ type: 'POST', url: '/FileService.asmx/UploadImage', // 替换成实际的服务URL data: JSON.stringify({ fileData: Array.from(new Uint8Array(files[0])), fileName: files[0].name }), contentType: 'application/json; charset=utf-8', dataType: 'json', success: function(response){ console.log('成功:', response.d); }, error:function(errorThrown){ console.error('错误:', errorThrown.statusText); } }); } // 下载图片 function downloadImage(fileName) { $.ajax({ type: 'GET', url: `/FileService.asmx/DownloadFile?strFilePath=/Images/${encodeURIComponent(fileName)}`, xhrFields: { responseType: 'blob' }, success: function(blob) { const link=document.createElement('a'); link.href=window.URL.createObjectURL(blob); link.download=fileName; link.click(); }, error: function(xhr,status,errorThrown){ alert('下载失败:' + status); } }); } ``` 这段JavaScript脚本提供了两种主要的功能——上传和下载图片。前者收集来自HTML输入控件中的文件信息并通过JSON序列化后提交给服务器侧的`UploadImage`方法;后者则是向`DownloadFile`发出带有目标文件名称查询参数的HTTP GET请求,在获取到Blob类型的响应之后触发浏览器自动下载行为[^2]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值