WebService中實現 上傳下載檔案

來源:互聯網
上載者:User

/*上傳檔案的WebService*/

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.IO;

/// <summary>
/// Upload 的摘要說明。
/// </summary>
[WebService(Namespace = "http://tempuri.org/",
   Description = "在Web Services裡利用.NET架構進上傳檔案。")]
public class UploadFile : System.Web.Services.WebService
{
    public UploadFile()
    {
    }

    [WebMethod(Description = "Web 服務提供的方法,返回是否檔案上傳成功與否。")]
    public string Upload(byte[] fs, string fileType)
    {
        string FileName = System.DateTime.Now.ToString("yyyyMMddHHmmssms") +"." +fileType;
        try
        {
            ///定義並執行個體化一個記憶體流,以存放提交上來的位元組數組。
            MemoryStream m = new MemoryStream(fs);
            ///定義實際檔案對象,儲存上傳的檔案。
            FileStream f = new FileStream(Server.MapPath(".") + "\\UploadFile\\"
             + FileName, FileMode.Create);
            ///把內記憶體裡的資料寫入物理檔案
            m.WriteTo(f);
            m.Close();
            f.Close();
            f = null;
            m = null;
            return FileName;
        }
        catch (Exception ex)
        {
            return null;
        }
    }

    [WebMethod(Description = "Web 服務提供的方法,刪除指定檔案")]
    public void Delete(string fileName)
    {
        string filePath = Server.MapPath(".") + "\\UploadFile\\" + fileName;      
        File.Delete(filePath);
    }
}

 

/*下載檔案*/

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.IO;

/// <summary>
/// GetBinaryFile 的摘要說明。
/// Web Services名稱:GetBinaryFile
/// 功能:返回伺服器上的一個檔案對象的二進位位元組數組。
/// </summary>
[WebService(Namespace = "http://tempuri.org/",
Description = "在Web Services裡利用.NET架構進行傳遞二進位檔案。")]
public class GetBinaryFile : System.Web.Services.WebService
{
    /// <summary>
    /// Web 服務提供的方法,返回給定檔案的位元組數組。
    /// </summary>
    [WebMethod(Description = "Web 服務提供的方法,返回給定檔案的位元組數組")]
    public byte[] GetFile(string requestFileName)
    {
        string fileName = Server.MapPath(".") + "\\UploadFile\\" + requestFileName;
        return getBinaryFile(fileName);
    }

    /// <summary>
    /// getBinaryFile:返回所給檔案路徑的位元組數組。
    /// </summary>
    /// <param name="filename"></param>
    /// <returns></returns>
    public byte[] getBinaryFile(string filename)
    {
        if (File.Exists(filename))
        {
            try
            {
                ///開啟現有檔案以進行讀取。
                FileStream s = File.OpenRead(filename);
                return ConvertStreamToByteBuffer(s);
                s.Close();
            }
            catch (Exception e)
            {
                return new byte[0];
            }
        }
        else
        {
            return new byte[0];
        }
    }

    /// <summary>
    /// ConvertStreamToByteBuffer:把給定的檔案流轉換為二進位位元組數組。
    /// </summary>
    /// <param name="theStream"></param>
    /// <returns></returns>
    public byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream)
    {
        int b1;
        System.IO.MemoryStream tempStream = new System.IO.MemoryStream();
        while ((b1 = theStream.ReadByte()) != -1)
        {
            tempStream.WriteByte(((byte)b1));
        }
        return tempStream.ToArray();

    }

    [WebMethod(Description = "Web 服務提供的方法,返回給定檔案類型。")]
    public string GetImageType()
    {
        ///這裡只是測試,您可以根據實際的檔案類型進行動態輸出
        return "image/jpg";
    }
}

/*調用上傳*/

string filePath = "c:\test.jpg";
FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate,
FileAccess.Read);
// Read the Data into the Byte Array
byte[] fileByte = new byte[fs.Length];
fs.Read(fileByte, 0, (int)fs.Length);

UploadFile uploadfile = new UploadFile();
int indexof = filePath.LastIndexOf(".")+1;
string fileExt = filePath.Substring(indexof, filePath.Length - indexof);
string filename = uploadfile.Upload(fileByte, fileExt);

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.