@manhng

Welcome to my blog!

jQuery Ajax submit a Multipart Form Data

August 18, 2021 15:01

jQuery Ajax submit a Multipart Form Data (edit)

JQuery Ajax Form Submit with FormData Example (nicesnippets.com)

jQuery Ajax File Upload with Form Data using PHP (onlinewebtutorblog.com)

AJAX Image and File Upload in PHP with jQuery (cloudways.com)

jQuery Ajax submit a multipart form - Mkyong.com (HAY HAY HAY)

jquery ajax basic authentication Code Example (codegrepper.com) (HAY HAY HAY)

javascript - Form Upload File to a Web API that Requires a Custom Header - Stack Overflow (HAY HAY HAY)

$.ajaxSetup({
    headers: { "X-API-KEY": "Abc@123" }
});
$.ajax({
  url: url,
  beforeSend: function(xhr) {
    xhr.setRequestHeader("X-API-KEY", "Abc@123");
  },
  success: function(data) {
  }
});

1) Backend: ASP.NET Core 5.0 Web API 

How To Upload Files With .NET Core Web API and Angular (code-maze.com)

CodeMazeBlog/dotnet-core-file-upload: This repository contains source code for the "Uploading Files With .NET Core Web API" article on the Code Maze blog (github.com)

CodeMazeBlog/dotnet-core-file-upload at end-project (github.com) (HAY HAY HAY)

How to read request headers in ASP.NET Core 5 MVC | InfoWorld (HAY HAY HAY) 

Secure ASP.NET Core Web API using API Key Authentication - Coding Sonata (HAY HAY HAY)

Secure ASP.NET Core Web API using API Key Authentication - CodeProject (HAY HAY HAY)

Startup

ConfigureServices(IServiceCollection services)

 services.AddCors(...);

services.Configure<FormOptions>(o =>
{
o.ValueLengthLimit = int.MaxValue;
o.MultipartBodyLengthLimit = int.MaxValue;
o.MemoryBufferThreshold = int.MaxValue;
});

services.AddControllers();

Configure(IApplicationBuilder app, IWebHostEnvironment env)

 app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"StaticFiles")),
RequestPath = new PathString("/StaticFiles")
});

app.UseRouting();

Controller

[HttpPost, DisableRequestSizeLimit]
public IActionResult Upload()
{
try
{
var file = Request.Form.Files[0];
var folderName = Path.Combine("StaticFiles", "Images");
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);

if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
var fullPath = Path.Combine(pathToSave, fileName);
var dbPath = Path.Combine(folderName, fileName);

using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}

return Ok(new { dbPath });
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}

2) Frontend: jQuery + Bootstrap + HTML5

<!DOCTYPE html>
<html>
<head>
<title>Register</title>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

<h1>Register</h1>

<form class="form-horizontal" action="https://localhost:44388/api/v1/Store/Register" method="post" enctype="multipart/form-data">
<fieldset>

<!-- Form Name -->
<legend>Form Name</legend>

<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="selectbasic">Select Basic</label>
<div class="col-md-4">
<select id="selectbasic" name="selectbasic" class="form-control">
<option value="1">Option one</option>
<option value="2">Option two</option>
</select>
</div>
</div>

<!-- Multiple Radios -->
<div class="form-group">
<label class="col-md-4 control-label" for="radios">Multiple Radios</label>
<div class="col-md-4">
<div class="radio">
<label for="radios-0">
<input type="radio" name="radios" id="radios-0" value="1" checked="checked">
Option one
</label>
</div>
<div class="radio">
<label for="radios-1">
<input type="radio" name="radios" id="radios-1" value="2">
Option two
</label>
</div>
</div>
</div>

<!-- Multiple Checkboxes (inline) -->
<div class="form-group">
<label class="col-md-4 control-label" for="checkboxes">Inline Checkboxes</label>
<div class="col-md-4">
<label class="checkbox-inline" for="checkboxes-0">
<input type="checkbox" name="checkboxes" id="checkboxes-0" value="1">
1
</label>
<label class="checkbox-inline" for="checkboxes-1">
<input type="checkbox" name="checkboxes" id="checkboxes-1" value="2">
2
</label>
<label class="checkbox-inline" for="checkboxes-2">
<input type="checkbox" name="checkboxes" id="checkboxes-2" value="3">
3
</label>
<label class="checkbox-inline" for="checkboxes-3">
<input type="checkbox" name="checkboxes" id="checkboxes-3" value="4">
4
</label>
</div>
</div>


<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Text Input</label>
<div class="col-md-4">
<input id="textinput" name="textinput" type="text" placeholder="placeholder" class="form-control input-md">
<span class="help-block">help</span>
</div>
</div>


<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="filebutton">File Button</label>
<div class="col-md-4">
<input id="filebutton" name="filebutton" class="input-file" type="file">
</div>
</div>

<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="singlebutton">Single Button</label>
<div class="col-md-4">
<button type="submit" value="Register" id="singlebutton" name="singlebutton" class="btn btn-primary">Register</button>
<button type="reset" value="Reset" class="btn btn-primary">Reset</button>
</div>
</div>

</fieldset>
</form>

</body>
</html>

3) Frontend: PHP

HTML

<!DOCTYPE html>
<html>
<body>

<h1>jQuery Ajax submit Multipart form</h1>

<form method="POST" enctype="multipart/form-data" id="fileUploadForm">
<input type="text" name="extraField"/><br/><br/>
<input type="file" name="files"/><br/><br/>
<input type="file" name="files"/><br/><br/>
<input type="submit" value="Submit" id="btnSubmit"/>
</form>

<h1>Ajax Post Result</h1>
<span id="result"></span>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

</body>
</html>

JavaScript

$(document).ready(function () {

$("#btnSubmit").click(function (event) {

//stop submit the form, we will post it manually.
event.preventDefault();

// Get form
var form = $('#fileUploadForm')[0];

// Create an FormData object
var data = new FormData(form);

// If you want to add an extra field for the FormData
data.append("CustomField", "This is some extra data, testing");

// disabled the submit button
$("#btnSubmit").prop("disabled", true);

$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/api/upload/multi",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {

$("#result").text(data);
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);

},
error: function (e) {

$("#result").text(e.responseText);
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);

}
});

});

});

Categories

Recent posts