How to Upload Files using ajax call in asp.net?

江枫思渺然 提交于 2021-01-28 06:32:26

问题


I have created a small asp.net web forms application, to manage emails , i have created a little interface contains mandatory information to send a email, like from , to , subject etc. now i want to attach files to the email, i have used asp.net file upload controller to upload files, and have to attach multiple files,

Now i want to send this details to code behind, so i thought the best way is to use ajax calls , because i don't want to refresh my page, but i can't figure out the way how to send the attached files to the server side, i have read some articles and they saying i have to use FormData to send the files , then i have created a FormData object and appended all the attached files to the object.but how to pass this object to server side, my js code as below,

function sendEmail() {

    var data = new FormData();
    var files = $('.attachment');
    $.each(files, function (key, value) {
        var file = $(value).data('file');
        data.append(file.name, file);
    });

    $.ajax({
        url: "OpenJobs.aspx/sendEmail",
        type: "POST",
        async: false,
        contentType: false, // Not to set any content header  
        processData: false, // Not to process data  
        data: null,
        success: function (result) {
            alert(result);
        },
        error: function (err) {
            alert(err.statusText);
        }
    });

}

Any help?


回答1:


You need to use Generic handler to upload files using ajax, try below code:

function sendEmail() {

var formData = new FormData();
var files = $('.attachment');
$.each(files, function (key, value) {
    var file = $(value).data('file');
    formData.append(file.name, file);
});

$.ajax({
    url: "FileUploadHandler.ashx",
    type: "POST",
    contentType: false, // Not to set any content header  
    processData: false, // Not to process data  
    data: formData,
    success: function (result) {
        alert(result);
    },
    error: function (err) {
        alert(err.statusText);
    }
});
}

Generic handler

<%@ WebHandler Language="C#" Class="FileUploadHandler" %>    

using System;    
using System.Web;    

public class FileUploadHandler : IHttpHandler  
{    

public void ProcessRequest (HttpContext context)  
{    
    if (context.Request.Files.Count > 0)    
    {    
        HttpFileCollection files = context.Request.Files;    
        for (int i = 0; i < files.Count; i++)    
        {    
            HttpPostedFile file = files[i];    
            string fname = context.Server.MapPath("~/uploads/" + file.FileName);    
            file.SaveAs(fname);    
        }    
        context.Response.ContentType = "text/plain";      
    }    

}      
}   


来源:https://stackoverflow.com/questions/44475698/how-to-upload-files-using-ajax-call-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!