我正在开发一个与WebApi .NET项目通信的Android应用程序,以便从数据库中插入和获取日期,这是常见的情况。 我尝试过使用Multipart 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;
}
我能够获取有关上传文件的文件名和其他信息。我怎样才能获得与上传文件关联的字节数组,以便将其保存在MS SQL Server中?也许最好在可访问的文件夹中重新创建图片,而不是将其存储在数据库中......
有人可以帮我吗?
答案 0 :(得分:3)
根据您的要求,您可以参考以下示例代码:
// 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;
希望它有所帮助!
P / S:你可以阅读更多here。