Uploading large files from android to c# asmx web service using Multipart Entity

1.5k Views Asked by At

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;
    }
1

There are 1 best solutions below

1
On BEST ANSWER

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);
        }
    }