How to upload image in ASP.NET MVC 4 using ajax or any other technique without postback?

前端 未结 7 1763
鱼传尺愫
鱼传尺愫 2020-12-05 05:40

I am developing a website in MVC 4, where user fill some information and save it to upload. all the information except image is being saved on server using Javascript, Json

7条回答
  •  清歌不尽
    2020-12-05 06:22

    There are two ways to post files (images) asynchronously If your target browsers support file api, you can use the following: HTML:

    
    

    JavaScript

    // Call this function on upload button click after user has selected the file 
    function UploadFile() {
        var file = document.getElementById('etlfileToUpload').files[0];
        var fileName = file.name;    
        var fd = new FormData();    
        fd.append("fileData", file);    
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener("progress", function (evt) { UploadProgress(evt); }, false);
        xhr.addEventListener("load", function (evt) { UploadComplete(evt); }, false);
        xhr.addEventListener("error", function (evt) { UploadFailed(evt); }, false);
        xhr.addEventListener("abort", function (evt) { UploadCanceled(evt); }, false);
        xhr.open("POST", "{URL}", true); 
        xhr.send(fd);
    }
    
    
    function UploadProgress(evt) {
        if (evt.lengthComputable) {
            var percentComplete = Math.round(evt.loaded * 100 / evt.total);
            $("#uploading").text(percentComplete + "% ");        
        }
    }
    
    function UploadComplete(evt) {
        if (evt.target.status == 200)
            alert(evt.target.responseText);
        else {
            alert("Error Uploading File");
        }
    }
    
    function UploadFailed(evt) {    
        alert("There was an error attempting to upload the file.");
    }
    
    function UploadCanceled(evt) {    
        alert("The upload has been canceled by the user or the browser dropped the connection.");
    }
    

    or you can use swf tools like uploadify

提交回复
热议问题