我正在通过多部分实体请求从安卓获取请求数据。 如何接受该请求并将文件保存在服务器端。请检查已尝试的代码。来自安卓的文件是视频文件。
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public UploadFileResponse FileUpload(FileStream stream)
{
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Clear();
Context.Response.ContentType = "application/json";
UploadFileResponse _response = null;
bool IsFileUploaded = false;
if (_response != null)
{
return _response;
}
else
{
_response = new UploadFileResponse();
}
try
{
MultipartParser parser = new MultipartParser(stream);
if (parser.Success)
{
string fileName = parser.Filename;
string contentType = parser.ContentType;
byte[] fileContent = parser.FileContents;
FileStream fileToupload = new FileStream("D:\FileUpload\" + fileName, FileMode.Create);
fileToupload.Write(fileContent, 0, fileContent.Length);
fileToupload.Close();
fileToupload.Dispose();
_response.Result = true;
_response.Message = "Success";
stream.Close();
}
else
{
_response.Result = false;
_response.Message = "Oops, something went wrong, please try again.";
}
}
catch (Exception ex)
{
_response.Result = false;
_response.Error = ex.Message;
_response.Message = "Oops, something went wrong, please try again.";
}
finally
{
}
return _response;
}
如果成功地将多部分数据发送到 Web 服务,则应该能够使用 HttpContext.Current.Request 捕获传入文件。
下面的代码会将文件保存到 Web 服务所在的当前目录。
[WebMethod]
public void AttachFiles()
{
HttpPostedFile file = HttpContext.Current.Request.Files[0];
using (var fileStream = new System.IO.FileStream(AppDomain.CurrentDomain.BaseDirectory+file.FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
file.InputStream.CopyTo(fileStream);
}
}