0

I am getting request data from android which is through multipart entity request. how to accept that request and save the file in server side. Please check the code which is have tried. the file which coming from android is video file.

[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;
    }
Shreekant
  • 111
  • 2
  • 11

1 Answers1

0

If you are successfully sending the multipart data to web service, you should be able to catch incoming files by using HttpContext.Current.Request.

Below code will save the file to current directory where your web service resides.

[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);
        }
    }
Ercan
  • 246
  • 2
  • 8
  • Hi... I am getting below exception on this line HttpPostedFile file = HttpContext.Current.Request.Files[0]; when i hit the service. 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index' – Shreekant Dec 12 '14 at 07:42