如何使用带有web Api的byte []返回文件?

问题描述 投票:1回答:1

我尝试使用web Api导出文件。

这是我的客户代码:

exportLicense(licenseIds) {
    return this.$http({
        method: 'POST',
        contentType: "application/zip",
        url: this.application.resolveWebApiService('Licenses', 'ExportLicenses'),
        data: licenseIds
    }); 
}

从我的后端(mycontroller.cs)函数导出ExportLicenses方法,如下所示:

[HttpPost]
[Route("ExportLicenses")]
public async Task<IHttpActionResult> ExportLicenses([FromBody] int[] licenseIds)
{
    Contract.Requires(ModelState != null);

    if (!ModelState.IsValid)
    {
        return CustomReturnMessage(CustomHttpStatusCode.UnprocessableEntity, "Bad request", Request, ResponseMessage);
    }

    var task = exportLicensesTaskFactory(licenseIds);
    var taskResult = await task.TryRunAsync();
    if (!taskResult.Item1 || taskResult.Item2 == null)
    {
        return CustomReturnMessage(422, $"Failed to import license file:\n{task.Exception}", Request, ResponseMessage);
    }

    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new ByteArrayContent(taskResult.Item2); //taskResult.Item2 is a byte[] 
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
    return ResponseMessage(response);

            //return Content(HttpStatusCode.OK, taskResult.Item2);
}

我不需要执行任何文件/ zip操作,因为我的任务已经执行此操作并且它向我返回一个byte []。(taskResult.Item2)

我的服务返回响应如下:(像一个损坏的字符串)

res.data
"PK-    Њ"LH,����������4  ORDER_AVEA_0001_10042_PMEXCH003_20175211_License.xml  .            �UY��F}���0�W+�b`4w"�}��%b���ί�57�w�EQ�~�:�T�]�s>~]��eJa�5��W�������O�4F���*5e�'��ߗ>�����A�y~���E�?�*|����7������gۗ�>��ɧ������o����b�i[6k���3���b�4K�]'RÚ���˥��D�ٝ)J!g�������
�a�7+bx��w�6���q�+�L�}�G�̐2�4�$GZk�;hg[�t$�s�۵s��m���&I?-]8 E��+�B�,N�>��!��
`o
��~'�w�| ?�*�����}.<0�E߿����    �<�N����
����:�1}}A�Fh�z��a�
�����,@Q�k�?o����)u����l�e���g��Y�^��Ľ�\�tF�mK�-�lH2�MҞ)�m�s�r�*�����~��,���o���/��XD�Au�y6/�tS-Q�V��rA��_jg����7{��x,�{�虜��w���*D{�Ǖ0��u��*.奟��#<�ܑ��k�H�k"oi=����]�2��2�5���<v2_f=e)z�K4Ͽ(7O�ET�)x���^���Q�X���!R�䰯
-&S]v��������fl: ��9��V{sf�)�:Ĉ\e�Cjm�e��G[��z%��z�<wNƅ�M�'�a>��v�zR-ɛ���鱍T7(�37�r[�ɻ&��ڻ�E�L�ie�زO�da��쵸Q��    18#r��N[�Y�?�]j�0�Mk0^�ۏ؍?Fg^�.Xp|n�e��`����N:&M �Z+��o��6��~�
�wـw��4��   ��n�$��.��[)��Bb��8![*�L|���&Jf�Tc�u@?Ƃ���1�o��B�XW�[hFr.�]��y��+^���������U�d�T��9�]{��K���ẍ́���!Y������7�<Ώ���-F_��:u�f����Iasr~F�u�9�`�M�O���
�m�p��a���1T�&����y%3*��]H[G    �r�]u�nk^+'�y�#���8��T�x-G*p�\(}q��8.�b^�Aٟz�^�.��<��SO$d�tT"�r)8Щ�wB�;NB����<S-�[�EBVǽ�č�I��-�z-��0���k7y~J��/\g   ti�������z"x9L#P�_���S�ة6�z�T�X�N��_h�l�'��k�)I>]��W7�`fK�@~�/q�:���@���}�Ow�G��������PK3 -    Њ"LH,����������4                ORDER_AVEA_0001_10042_PMEXCH003_20175211_License.xml  .            PK      v   �    "
c# arrays asp.net-web-api http-post zipfile
1个回答
0
投票

我们可以使用这样的东西:

postdownload: function (url, fileName, data) {
            authenticationService.getAuthenticationToken().then(function (token) {
                var form = document.createElement("form");
                form.setAttribute("method", "post");
                form.setAttribute("action", url);
                $('<input>').attr({ name: 'authToken', type: 'hidden' }).val('Bearer ' + token).appendTo(form);
                $('<input>').attr({ name: 'fileName', type: 'hidden' }).val(fileName).appendTo(form);
                $('<input>').attr({ name: 'data', type: 'hidden' }).val(data).appendTo(form);
                document.body.appendChild(form);
                form.submit();
                $('form > input[name=authToken]').val('');
                $('form > input[name=fileName]').val('');
                $('form > input[name=data]').val('');
            }, function (reason) {
                return $q.reject({
                    config: config,
                    headers: {},
                    status: 0,
                    data: null
                });
            });
        }

我们应该像这样打电话:

var serialized = JSON.stringify(licenseIds);
        var url = this.application.resolveWebApiService('Licenses', 'ExportLicenses?' + idsString + '');
        this.uiHelper.postdownload(url, "asd.zip", serialized);

并编辑了我的后端代码,如下所示:

var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new ByteArrayContent(taskResult.Item2);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
            return ResponseMessage(response);
© www.soinside.com 2019 - 2024. All rights reserved.