Skip to content

Instantly share code, notes, and snippets.

@dejanvasic85
Last active August 11, 2017 06:49
Show Gist options
  • Save dejanvasic85/54a1d4cd8d2c391c7e30327e067328a0 to your computer and use it in GitHub Desktop.
Save dejanvasic85/54a1d4cd8d2c391c7e30327e067328a0 to your computer and use it in GitHub Desktop.
Asp.net WebForms multiple file upload
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Http;
namespace TestFileUpload
{
public class FileUploadController : ApiController
{
[HttpPost]
public IHttpActionResult UploadFile()
{
if (!HttpContext.Current.Request.Files.AllKeys.Any())
{
return BadRequest();
}
foreach (var key in HttpContext.Current.Request.Files.AllKeys)
{
var httpPostedFile = HttpContext.Current.Request.Files.Get(key);
if (httpPostedFile != null)
{
var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName);
httpPostedFile.SaveAs(fileSavePath);
}
}
return Ok();
}
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUploadTest.aspx.cs" Inherits="TestFileUpload.FileUploadTest" %>
<%@ Register Src="~/WebUserControl1.ascx" TagPrefix="uc1" TagName="WebUserControl1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var $fileUpload = $("#fileUpload");
$('#btnUploadFile').on('click', function () {
var data = new FormData();
var files = $fileUpload.get(0).files;
if (files.length === 0) {
alert('Please select at least 1 file before uploading.');
return;
}
for (var i = 0; i < files.length; i++) {
data.append("key-" + i, files[i]);
}
$.ajax({
type: "POST",
url: "/api/fileupload/uploadfile",
contentType: false,
processData: false,
data: data
}).done(function (responseData, textStatus) {
if (textStatus !== 'success') {
alert('something bad happened!'); // Todo - better message to user here!
return;
}
$fileUpload.val('');
alert('success!!!'); // Todo - better message to user here. Look at toastr Javascript library
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<label for="fileUpload">Select File to Upload:</label>
<input type="file" id="fileUpload" multiple="multiple" />
<br />
<input type="button" value="Upload File" id="btnUploadFile" />
</div>
<uc1:WebUserControl1 ID="WebUserControl11" runat="server" />
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment