I have a form in which I have to save a pdf from the client to the server, I am using MVC with the following structure:
VIEW:
@using (Html.BeginForm("", "FormularioPdf", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.Partial("_Formulario");
}
PARTIAL VIEW:
<div class="form-group">
<label class="label-color" for="numTarjeta">Documento PDF:</label>
<input type="file" class="form-control" id="docupdf" name="docupdf" accept="application/pdf">
</div>
JAVASCRIPT:
function GuardarDocumento(documento) {
try {
var cont = $('#docupdf').get(0).files.length;
if (cont == 1) {
var data = new FormData();
var files = $("#docupdf").get(0).files;
if (files.length > 0) {
console.log("files", files[0]);
data.append("file", files[0]);
}
var ajaxRequest = $.ajax({
type: "POST",
url: "PdfUpload",
contentType: false,
processData: false,
data: data
});
ajaxRequest.done(function (xhr, textStatus) {
// Do other operation
});
}
} catch (e) {
console.log("Error view",e)
}
}
CONTROLLER:
[HttpPost]
public ActionResult PdfUpload()
{
try
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/pdf/"), fileName);
file.SaveAs(path);
}
}
} catch(Exception e)
{
Debug.WriteLine("Error: " + e);
}
return View();
}
When inserting a file already saved in the input and performing the POST, the 500 jumps
How can I prevent that error?
To prevent this error, in the controller you have to add a path check with
System.IO.File.Exists(path)
In my case the code has been as follows: