Thursday, 14 May 2015

AngularJS with save file using fileupload control

For save file in binary

[AllowAnonymous]
        public async System.Threading.Tasks.Task<HttpResponseMessage> PostMemberImage(int customerID, int memberID)
        {
            AjaxResult res = new AjaxResult();
            HttpRequestMessage request = this.Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            if (!System.IO.Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(@"~/App_Data/uploads")))
            {
                System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(@"~/App_Data/uploads"));
            }

            string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");

            var provider = new MultipartFormDataStreamProvider(root);
            // System.Threading.Tasks.Task<byte[]> img ;
            byte[] img1 = new byte[1024];
            var task = await request.Content.ReadAsMultipartAsync(provider).
                ContinueWith<HttpResponseMessage>(o =>
                {


                    ///MY CODE///
                    FileStream fsOld = new FileStream(provider.FileData[0].LocalFileName, FileMode.Open, FileAccess.Read);

                    CreateThumbnail(fsOld.Name, 166, 166);

                    FileStream fs = new FileStream(provider.FileData[0].LocalFileName + "_thumb", FileMode.Open, FileAccess.Read);
                    BinaryReader br = new BinaryReader(fs);

                    byte[] image = br.ReadBytes((int)fs.Length);

                    br.Close();
                    var filepath = fs.Name;
                    var maxfilepath = fsOld.Name;
                    fs.Close();
                    fsOld.Close();

                    ////MY CODE END///////////

                    _memberService.SaveMemberImage(memberID, image, customerID);

                    try
                    {
                        if (System.IO.File.Exists(filepath))
                        {
                            System.IO.File.Delete(filepath);
                        }

                        if (System.IO.File.Exists(maxfilepath))
                        {
                            System.IO.File.Delete(maxfilepath);
                        }
                    }
                    catch
                    {
                    }


                    return new HttpResponseMessage()
                    {
                        Content = new StringContent("File uploaded.")
                    };
                }
            );

            return task;
        }

For html side

   <input type="file" id="myFile" ng-model="myfiles" accept="text/xml" />
                                <button type="button" ng-click="myFunction(myfiles)" class="btn btn-xs btn-purple mrg-t-5"><i class=" icon-cloud-upload"></i> Upload</button>

From JS
$scope.model = {
            name: "",
            type: ""
        };
$scope.myFunction = function (obj) {

            var x = document.getElementById("myFile");
            var txt = "";
            if ('files' in myFile) {
                if (x.files.length > 0 && x.files[0].type != "text/xml") {
                    toastr.error('Please import xml file only !'); return;
                }
                if (x.files.length == 0) {
                    toastr.error("Select one or more files."); return;
                } else {

                    for (var i = 0; i < x.files.length; i++) {
                        var file = x.files[i];
                        if ('name' in file) {
                            txt += file.name + "&nbsp;&nbsp;&nbsp;";
                        }
                        if ('size' in file) {
                            txt += bytesToSize(file.size);
                        }
                    }
                }
                function bytesToSize(bytes) {
                    var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
                    if (bytes == 0) return '0 Byte';
                    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
                    return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
                };
                document.getElementById("demo").innerHTML = txt;
                //return false;
                if (x.files.length > 0 && x.files[0].type == "text/xml") {
                    $http({
                        method: 'POST',
                        url: httpServiceUrlForService + "api/GPROMemberImport/PostXMLFileupload?reportingyear=" + $scope.ReportYear,
                        headers: { 'Content-Type': undefined },//$scope.sourceID
                        transformRequest: function (data) {
                            //debugger

                            var formData = new FormData();
                            formData.append("model", angular.toJson(data.model));
                            formData.append("file", data.files);

                            if (data.files) {
                                $scope.message = 'Please wait, Document is uploading...';
                                $scope.showPrgress = true;
                            }

                            return formData;
                        },
                        data: { model: $scope.model, files: x.files[0] }
                    }).
                   success(function (data, status, headers, config) {
                       //alert("success!");
                       $scope.showPrgress = false;
                       $scope.message = '';
                       $scope.files = '';
                       angular.element("input[type='file']").val(null);
                       document.getElementById("demo").innerHTML = '';
                       toastr.success('Document uploaded successfully!'); return;
                   }).
                   error(function (data, status, headers, config) {
                       //alert("failed!");
                       $scope.showPrgress = false;
                       $scope.message = '';
                       toastr.error("Failed !"); return;
                   });
                }
            }
            else {
                if (x.value == "") {                   
                    toastr.error("Select one or more files!");
                } else {                  
                    txt += "The files property is not supported by your browser!";
                    txt += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
                    toastr.error(txt);
                }
            }
            //  document.getElementById("demo").innerHTML = txt;

        }

Now while showing uploaded image in UI

<img class="list_photo" ng-src="data:image/png;base64,{{o.MemberImage}}" />

13 comments:

  1. Thanks for sharing this saving file concepts. It is really helpful. Keep sharing more like this.
    AngularJS Training | AngularJS Training in Chennai | AngularJS course in Chennai

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Thanks for such a great article here. I was searching for something like this for quite a long time and at last I’ve found it on your blog. It was definitely interesting for me to read  about their market situation nowadays.
    Java training in Marathahalli | Java training in Btm layout

    Java training in Jaya nagar | Java training in Electronic city

    ReplyDelete
  4. This information is impressive. I am inspired with your post writing style & how continuously you describe this topic. Eagerly waiting for your new blog keep doing more.
    AWS Training in Chennai
    aws training in bangalore
    AWS Course in Chennai
    aws course in bangalore
    AWS Training centers in Chennai
    aws certification training in bangalore

    ReplyDelete
  5. Just stumbled across your blog and was instantly amazed with all the useful information that is on it. Great post, just what i was looking for and i am looking forward to reading your other posts soon!

    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  6. Thanks for post.I do agree your blog for quiz programming concepts, which is very helpful to grow up your knowledge. keep sharing more.,

    AWS training in chennai | AWS training in annanagar | AWS training in omr | AWS training in porur | AWS training in tambaram | AWS training in velachery

    ReplyDelete
  7. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.share some more.
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

    ReplyDelete
  8. There is a great announcement with a great offer only for you guys . We are here to tell you that our institution is offering CS executive classes and a free of cost CSEET classes. Hope you all wil enjoy it. So for availing this offer contact us or visit our website at https://uniqueacademyforcommerce.com/

    ReplyDelete
  9. nices information thanku so much this information
    thanku so much
    nices

    ReplyDelete
  10. There Are Many Complaints About XM REVIEW Broker In The Internet But You Should Read This Review Before Investing Your Money With Them. We Have Personally Tested XM Fx And Found It To Be A Scam, Avoid Them At All Costs!

    ReplyDelete