Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取web Api项目中上载文件的字节数组_C#_Android_Asp.net Web Api_Encoding_Bytearray - Fatal编程技术网

C# 获取web Api项目中上载文件的字节数组

C# 获取web Api项目中上载文件的字节数组,c#,android,asp.net-web-api,encoding,bytearray,C#,Android,Asp.net Web Api,Encoding,Bytearray,我正在开发一个Android应用程序,它与一个WebApi.NET项目进行通信,以便插入数据并从数据库中获取数据。 我尝试过使用多部分MIME。因此,我使用了以下代码: public async Task<HttpResponseMessage> ManageProfilePicture() { if (!Request.Content.IsMimeMultipartContent()) { throw new Http

我正在开发一个Android应用程序,它与一个WebApi.NET项目进行通信,以便插入数据并从数据库中获取数据。 我尝试过使用多部分MIME。因此,我使用了以下代码:

public async Task<HttpResponseMessage> ManageProfilePicture()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }
        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);

        var task = await Request.Content.ReadAsMultipartAsync(provider).
            ContinueWith<HttpResponseMessage>(t =>
            {
                if (t.IsFaulted || t.IsCanceled)
                {
                    Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                }

                String fileName = provider.FileData[0].Headers.ContentDisposition.FileName;
                return Request.CreateResponse(HttpStatusCode.OK);
            });

        return task;
    }
public异步任务ManageProfilePicture()
{
如果(!Request.Content.IsMimeMultipartContent())
{
抛出新的HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root=HttpContext.Current.Server.MapPath(“~/App_Data”);
var provider=新的MultipartFormDataStreamProvider(根);
var task=wait Request.Content.ReadAsMultipartAsync(提供程序)。
继续(t=>
{
如果(t.IsFaulted | | t.IsCanceled)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError,t.Exception);
}
字符串fileName=provider.FileData[0]。Headers.ContentDisposition.fileName;
返回Request.CreateResponse(HttpStatusCode.OK);
});
返回任务;
}
我能够得到文件名和其他有关上传文件的信息。如何获取与上载文件关联的字节数组,以便将其保存在MS SQL Server中?也许在可访问的文件夹中重新创建图片比将其存储在数据库中更好


有人能帮我吗

对于您的需求,您可以参考以下示例代码:

            // process incoming request            
            if (!Request.Content.IsMimeMultipartContent())
            {                
                // return error response               
            }

            // read the file and form data.
            ...
            await Request.Content.ReadAsMultipartAsync(provider);                           
            ...

            // check if files are on the request.
            if (provider.FileStreams.Count == 0)
            {                
                // return return error response               
            }

            IList<string> uploadedFiles = new List<string>();

            foreach (KeyValuePair<string, Stream> file in provider.FileStreams)
            {
                // get file name and file stream
                byte[] photo;
                string fileName = file.Key;
                using (Stream stream = file.Value)
                {
                    using (BinaryReader reader = new BinaryReader(stream))
                    {
                        photo = reader.ReadBytes((int)stream.Length);
                    }
                }

                // INSERT INTO DATABASE HERE (USING SqlConnection, SqlCommand...)                
                // ...

                // keep track of the filename and filelength for the response
                uploadedFiles.Add(fileName);
                uploadedFiles.Add(photo.Length.ToString("N0") + " bytes");
            }

            // return successful response;
//处理传入请求
如果(!Request.Content.IsMimeMultipartContent())
{                
//返回错误响应
}
//读取文件和表单数据。
...
wait Request.Content.ReadAsMultipartAsync(提供程序);
...
//检查文件是否符合请求。
if(provider.FileStreams.Count==0)
{                
//返回错误响应
}
IList uploadedFiles=新列表();
foreach(provider.FileStreams中的KeyValuePair文件)
{
//获取文件名和文件流
字节[]照片;
字符串文件名=file.Key;
使用(Stream=file.Value)
{
使用(BinaryReader=新的BinaryReader(流))
{
photo=reader.ReadBytes((int)stream.Length);
}
}
//在此处插入数据库(使用SqlConnection、SqlCommand…)
// ...
//跟踪响应的文件名和文件长度
uploadedFiles.Add(文件名);
uploadedFiles.Add(photo.Length.ToString(“N0”)+“bytes”);
}
//返回成功响应;
希望有帮助


p/S:您可以阅读更多。

不清楚您是想知道如何将图像作为字节数组发送到Web API,还是想知道如何将字节数组保存到SQL Server。另外,提供一些您已经尝试过的代码。要上传图片,我不会使用JSON。使用mutlipart表单上传和base64编码图片。试图直接用JSON上传大量照片通常会破坏任何JSON解析器。至少这是我在网上的经历。从未在android应用程序上执行过。@ThrowsException谢谢您的回答,我已经更新了我的问题,因为我已经实现了多部分表单。。。你能给我一些建议吗?