I noticed that you need a refresh on the whole page to get the server-side file. Would there be some way to refresh to perform this operation? I know it's possible with Ajax, what would it be like?
I noticed that you need a refresh on the whole page to get the server-side file. Would there be some way to refresh to perform this operation? I know it's possible with Ajax, what would it be like?
I've been using Ajax, I do not remember where I got the tutorial but my code looks like this:
HTML:
<form role="form" id="commentForm">
<input type="file" id="uploadEditorImage" accept="image/*" />
<button type="button" id="btnEnviar" data-loading-text="Enviando..." class="btn btn-primary">
Enviar
</button>
</form>
Ajax:
$("#btnEnviar").click(function () {
var dataForm = new FormData($("#commentForm")[0]);
var files = $("#uploadEditorImage").get(0).files;
if (files.length > 0) {
dataForm.append("HelpSectionImages", files[0]);
}
$.ajax({
url: '@Url.RouteUrl(new { action = "EnviaArquivo", controller = "Home" })',
type: "POST",
processData: false,
contentType: false,
data: dataForm,
success: function (response) {
console.log('sucesso');
console.log(response);
},
error: function (er) {
console.log('erro');
console.log(er);
}
});
});
Controller:
[WebMethod]
public string EnviaArquivo(FormCollection form)
{
HttpPostedFile arquivo = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
string path = "~/img/fotosDepoimentos/";
arquivo.SaveAs(Server.MapPath(path + arquivo.FileName));
return "Arquivo enviado com sucesso...";
}
The problem happens because an AsyncPostback is occurring, and to send the file it must be a regular PostBack. So, just add a PostbackTrigger force update of the UpdatePanel.
Assuming there is a "Submit" button inside the UpdatePanel, try:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="EnviarBtn" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="EnviarBtn" runat="server" />
More information: