我从android获取请求数据,这是通过多部分实体请求。如何接受该请求并将文件保存在服务器端。请检查已经尝试过的代码。来自android的文件是视频文件。
[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;
}
答案 0 :(得分:0)
如果您成功将多部分数据发送到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);
}
}