簡體   English   中英

在JavaScript中創建字節數組

[英]Create byte array in JavaScript

有沒有一種方法可以從JavaScript(或Typescript)文件中創建字節數組,該文件將發送到C#WebApi服務,並由C#字節數組方法參數使用? 如果是這樣,您可以提供一個JavaScript示例嗎?

我應該提到,這是一個將發布到該服務的Angular 4+應用程序。

我需要將Word文檔,PDF和圖像上載到C#服務,這是當前構建C#服務的方式。 期望要上傳的文件的字節數組。

這是C#服務的請求對象:

[DataContract]
public class SaveAttachmentRequest : BaseRequest
{
    [RestUrlParameter(Mode = UrlParameterMode.Inline)]
    [DataMember(IsRequired = true)] public AttachmentLookupInformation LookupInformation { get; set; } = new AttachmentLookupInformation();
    [DataMember(IsRequired = true)] public byte[] Attachment { get; set; } = null;
}

這是AttachmentLookupInformation類:

[DataContract]
public class AttachmentLookupInformation
{
    [DataMember(IsRequired = true)] public Guid Id { get; set; } = Guid.Empty;
    [DataMember(IsRequired = true)] public Guid LinkedToId { get; set; } = Guid.Empty;
    ///<summary>Not including the path- just the file name and extension.</summary>
    [DataMember(IsRequired = true)] public string FileName { get; set; } = string.Empty;
    [DataMember(IsRequired = true)] public int FileSizeInBytes { get; set; } = 0;
    ///<summary>MIME type.</summary>
    [DataMember(IsRequired = true)] public string ContentType { get; set; } = string.Empty;
    [DataMember(IsRequired = true)] public AttachmentCategories AttachmentCategory { get; set; } = AttachmentCategories.Unknown;
    [DataMember(IsRequired = true)] public string DownloadUrl { get; set; } = string.Empty;
    [DataMember(IsRequired = true)] public string CreatedBy { get; set; } = string.Empty;
    [DataMember(IsRequired = true)] public DateTimeOffset CreatedTimestamp { get; set; } = DateTimeOffset.MinValue;
}

這樣我就可以將文件和其他數據上傳到服務。

編輯:包括我使用的失敗的Angular代碼:

const lookupInfo = new AttachmentLookupInformation();
lookupInfo.Id = Helpers.emptyGuid;
lookupInfo.LinkedToId = this.contractId;
lookupInfo.AttachmentCategory = 10;

const request = new SaveAttachmentRequest();

const reader = new FileReader();
reader.onload = function() {
  const buffer = reader.result;
  let binary = '';
  const bytes = new Uint8Array(buffer);
  const length = bytes.byteLength;
  for (let i = 0; i < length; i++) {
    binary += String.fromCharCode(bytes[i]);
  }

  request.Attachment = binary;
  lookupInfo.ContentType = files[0].type;
  lookupInfo.FileName = files[0].name;
  lookupInfo.FileSizeInBytes = length;
};
reader.readAsArrayBuffer(files[0]);
reader.onloadend = function() {
  request.LookupInformation = lookupInfo;

  console.log('request: ', request);

  that.contractsService
    .save(request, 'attachment/saveattachment')
    .subscribe(res => {
      if (res.Success) {
        console.log('upload response: ', res);
      }
    });

};

好吧,你有:

that.contractsService
    .save(request, 'attachment/saveattachment')

但是您要顯示的類是SaveAttachmentRequest ,其中包含public byte[] Attachment 我認為,您的問題中沒有一個函數稱為saveattachment ,該類稱為attachment ,這是應該處理的數據傳輸到byte []的過程,除非您以某種方式直接將其設置為參數。 假設您具有此類attachment類,則應該在其中有一個名為saveattachment的入口點可以完成所有工作。 但是要說這失敗的,因為您正在傳遞JS模型並將其直接映射到.NET。 因此,創建一個可以接受您的二進制字符串的字符串參數,然后將其保存到您的byte[]

[DataMember(IsRequired = true)] public string strAttachment { get; set; } = null;

在你的JS里

request.Attachment = binary;

變成

request.strAttachment = binary;

然后,您需要:

public class attachment : ApiController
{
    [System.Web.Http.HttpPost]
    public JsonResult saveattachment(SaveAttachmentRequest sar, AttachmentLookupInformation ali)
    {          
        //string bits = "000011110000001000";
        string bits = sar.strAttachment;
        int numOfBytes = (int)Math.Ceiling(bits.Length / 8m);
        byte[] bytes = new byte[numOfBytes];
        int chunkSize = 8;

        for (int i = 1; i <= numOfBytes; i++)
        {
            int startIndex = bits.Length - 8 * i;
            if (startIndex < 0)
            {
                chunkSize = 8 + startIndex;
                startIndex = 0;
            }
            bytes[numOfBytes - i] = Convert.ToByte(bits.Substring(startIndex, chunkSize), 2);
        }

        sar.attachment = bytes;

        // ... do your other stuff for saving your model objects to the DB
        // using Entity Framework's data context, etc.
    }
}

那只是將二進制字符串轉換為byte []的一種方法。 這里還有很多其他方式。

或者,您是否嘗試過僅將其作為字符串發送,因此:

[DataMember(IsRequired = true)] public byte[] Attachment { get; set; } = null;

變成這個:

[DataMember(IsRequired = true)] public string Attachment { get; set; } = null;

首先?

在文件類型輸入更改事件中,您可以獲得字節數組。 應該對您有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM