How to find out why some files won't upload? - javascript

Using the code below, I can successfully upload an xlsx file without any issues, but when I try to upload a csv version of the same file it never hits the controller. So I tried other csv files and some of them work fine and others don't hit the controller.
No errors are raised so I don't really know what to do to troubleshoot this further. I'm not even sure how to isolate whether the issue is happening after asp.net gets the request but before it hits the controller, or whether it's before it even gets posted. Any suggestions on what I can look into next?
Html:
<div>
<input type="file" name="file" id="uploadFile" />
</div>
JavaScript:
$('#uploadFile').on('change', function (e) {
var files = e.target.files;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++)
data.append("file" + x, files[x]);
$.ajax({
type: "POST",
url: '/Home/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (result) {
if (result)
alert('File uploaded.');
else
alert('Error uploading file :(');
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
}
});
} else {
alert("This browser doesn't support HTML5 file uploads :(");
}
}
});
Controller:
[HttpPost]
public JsonResult UploadFile()
{
try
{
if(Request.Files.Count == 0)
throw new ArgumentException("No file to upload!");
var fileContent = Request.Files[0];
if(fileContent != null && fileContent.ContentLength > 0)
{
Session["ImportFileId"] = ImportFiles.Save(fileContent.InputStream);
return Json(true);
}
else
return Json(false);
}
catch(Exception)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(false);
}
}

Related

I want to upload an image to folder using javascript and generic handler in c#

function ajaxFileUpload(mode) {
var fupl = 'fileToUpload';
var fileName = $('#fileuploadbrand').val();
if (fileName == "" || fileName == null)//if user doesn't select an image
{
alert('Please Select An image');
}
else {
var vars = fileName.split("."); //get file extension.
if (vars[1].toString().toLowerCase() != "jpg")
{//check the file extension.
alert('The image format is not valid !');
return false;
}
$.ajax({
type: 'POST',
url: '../handlers/BandPictureHandler.ashx',
data: { Action: mode },
cache: false,
fileElementId: 'fileToUpload',
contentType: false,
processData: false,
success: function (data) {
if (data.result == "successed")
alert('Image Uploaded');
},
error: function (data) {
console.log("error");
console.log(data);
}
});
}
return false;
}
This is my javascript code. Where Using debugging I can see that file
is coming and it also hits the handler. But In the handler, It is not going to the "new" case. It always redirect to the default case. Below I am giving the handler code. Please help to to store the image in folder using javascript. If there is any easy step,then you can also suggest it to me.
public class BandPictureHandler : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string action = request["Action"];
switch (action)
{
case "NEW":
string result = "failed";
try
{
string fileName = SaveCaper(context);
result = "successed";
response.Write("{\"result\":" + result.ToString().ToLower() + "}");
}
catch
{
response.Write("{\"result\":" + result.ToString().ToLower() + "}");
}
break;
default:
break;
}
}
private string SaveCaper(HttpContext context)
{
string fileName = string.Empty;
string path = context.Server.MapPath("~/assets/media/brand/");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
try
{
var file = context.Request.Files[0];
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
{
string[] files = file.FileName.Split(new char[] { '\\' });
fileName = files[files.Length - 1];
}
else
{
fileName = file.FileName;
}
string strFileName = fileName;
fileName = Path.Combine(path, fileName);
try
{
file.SaveAs(fileName);
}
catch (Exception exp)
{
//log the exception
}
}
catch (Exception exp)
{
//log the exception
}
return fileName;
}
public bool IsReusable {
get {
return false;
}
}
}

JQuery check the file size from inside a function

So I have these Jquery code where the function will check the file extension and the file size from the input file. The checking for the file extension works fine, but the file size checking is not working, can you guys help me with this problem?
$(document).ready(function () {
/* Some other code
*/
var fileExtension = ['jpeg', 'jpg', 'png', 'pdf'];
var status = false;
function checkFile(fileinput){
if ($.inArray(fileinput.split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Tolong upload file dengan extensi: " + fileExtension.join(', '));
fileinput.value = "";
return status = false;
}
if (fileinput[0].size > 1048576) {
alert("The maximum file size is 1 mb");
fileinput.value = "";
return status = false;
}
else {
return status = true;
}
}
$('#btn_IdentitasKTP\\/Paspor').on('click', function () {
$('#file_IdentitasKTP\\/Paspor').trigger('click')
});
$('#file_IdentitasKTP\\/Paspor').change(function () {
var fileinput = $('#file_IdentitasKTP\\/Paspor').val();
checkFile(fileinput);
if (status == true) {
var file_name = this.value.replace(/\\/g, '/').replace(/.*\//, '');
$('#text_IdentitasKTP\\/Paspor').val(file_name);
status = false;
}
});
});
Try this :
$('#file_IdentitasKTP\\/Paspor').change(function () {
var fileinput = this.files;
...
you can check file size by :
console.log(fileinput[0].size)
For example to upload image by AJAX. You will simply write this code. You will size with object. it will return size of that object.
$(document).ready(function(e) {
$("#uploadimage").on('submit', (function(e) {
e.preventDefault();
formdata = new FormData(this);
if (formdata[0].size = < 1000) {
$.ajax({
url: "PHp File name path", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: formdata, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
} else {
alert("You can not Upload this file Please resize this image.")
}
}));
This is the updated code for this question.
$(document).ready(function () {
/* Some other code
*/
var fileExtension = ['jpeg', 'jpg', 'png', 'pdf'];
var status = false;
function checkFile(fileinput){
if ($.inArray(fileinput[0].name.split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Tolong upload file dengan extensi: " + fileExtension.join(', '));
fileinput.value = "";
return status = false;
}
if (fileinput[0].size > 1048576) {
alert("Tolong upload file dengan ukuran dibawah 1mb");
fileinput.value = "";
return status = false;
}
else {
return status = true;
}
}
$('#btn_IdentitasKTP\\/Paspor').on('click', function () {
$('#file_IdentitasKTP\\/Paspor').trigger('click')
});
$('#file_IdentitasKTP\\/Paspor').change(function () {
var fileinput = this.files;
checkFile(fileinput);
if (status == true) {
var file_name = this.value.replace(/\\/g, '/').replace(/.*\//, '');
$('#text_IdentitasKTP\\/Paspor').val(file_name);
status = false;
}
});
});

404 after posting a big file with .net

I have the following JS code, this function calls a WEBAPI service which receives a file and saves it to the server.
Please check the .onfail,
File size is 500MB
function GuardarOrigen() {
var NombreOrigen = $("#Nombre").val()
if (NombreOrigen == '') {
info('Debe ingresar un nombre');
return;
}
var rgx = new RegExp("^[a-zA-Z0-9]+$");
if (!rgx.test(NombreOrigen)) {
info('El nombre no debe tener espacios en blanco ni caracteres especiales.');
return;
}
var files = $('#Archivo').get(0).files;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
}
$("#bntGuardar").prop('disabled', true);
$("#imgLoader").show();
$.ajax({
url: urlCrearOrigen + '?NombreOrigen=' + NombreOrigen,
method: "POST",
contentType: false,
processData: false,
data: data,
success: function (result) {
info("Guardado con éxito.");
window.location.href = urlEditarOrigen + result
},
}).fail(function (jqXHR, textStatus) {
info("Error guardando el origen");
console.log('Error:' + jqXHR.responseText + textStatus);
}).always(function () {
$("#imgLoader").hide();
$("#bntGuardar").prop('disabled', false);
});
}
} else {
info('Debe seleccionar el archivo');
}
}
On the WEB API Controller I have this code:
[HttpPost]
[Route("/CrearOrigen")]
public async System.Threading.Tasks.Task<HttpResponseMessage> CrearOrigen(string NombreOrigen)
{
if (!Request.Content.IsMimeMultipartContent())
{
return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "No se recibieron archivos");
}
string root = HttpContext.Current.Server.MapPath("~/App_Data/CargaOrigenes");
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
var provider = new MultipartFormDataStreamProvider(root);
await Request.Content.ReadAsMultipartAsync(provider);
if (provider.FileData.Count == 0)
{
return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Parámetros invalidos - sin archivo");
}
string FileName = provider.FileData[0].LocalFileName;
string[] FileParts = provider.FileData[0].LocalFileName.Split(Convert.ToChar("."));
string FileExt = String.Empty;
if (provider.FileData[0].Headers.ContentDisposition.FileName.Contains(".csv"))
{
FileExt = "csv";
}
else
{
return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Archivo no soportado");
}
try
{
CargasMasivasManager cmm = new CargasMasivasManager();
int idOrigen = cmm.CrearOrigen(FileName, FileExt, NombreOrigen);
return this.Request.CreateResponse(HttpStatusCode.OK, idOrigen.ToString());
}
catch (Exception e)
{
return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
}
}
After 10 or 15 minutes I get a 404, the resource you are looking for is not on the server or is unavailable.
However when the files are smaller the process works fine.
Also, this works locally but when deployed on one server I get the error, and I cant debug on the server because I cant install Visual studio there.
Try updating your web.config to allow a large file
<configuration>
<system.web>
<httpRuntime maxRequestLength="xyz" />
</system.web>
</configuration>
xyz are in KB, so 2048kb = 2mb.
So 500mb = 512000kb

Ajax File Upload Not Working for IE8

I'm having trouble uploading a file using a Javascript function that makes an Ajax call to a servlet. The file is uploaded perfectly when I use chrome, but not when I use IE8 (Go figure).
I used to have a file select button on the bottom of my form. When I clicked that button a function would be called and it would upload the file to the servlet using ajax. This worked perfectly in IE8, but the client wanted links instead. So now I have the links in the form, and the buttons hidden with css. The links call the click event of the buttons. Now the file uploading only works with Chrome, and not IE8.
The request never makes it to the servlet for some reason, and for some reason the ajax request returns success. Any idea what the problem might be?
Here is my code:
//Uploading a file
$("#uploaded_file").change(function() {
var filename = $(this).val();
if(isAcceptable(filename)) {
$.ajaxFileUpload
(
{
type: "POST",
url:'GenerateServlet',
secureuri:false,
fileElementId:'uploaded_file',
dataType: 'json',
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.msg);
}
}
fillTemplate(data);
}
}
)
}
else if(filename.length > 0){
$("#uploaded_file").val("");
alert("Invalid File! Please select another file")
}
});
$("#upload_link").click(function() {
document.getElementById('uploaded_file').click();
return false;
});
Here is the upload function:
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if(window.ActiveXObject)
{
if(typeof uri== 'boolean'){
iframeHtml += ' src="' + 'javascript:false' + '"';
}
else if(typeof uri== 'string'){
iframeHtml += ' src="' + uri + '"';
}
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body);
return jQuery('#' + frameId).get(0);
},
createUploadForm: function(id, fileElementId, data)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if(data)
{
for(var i in data)
{
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
Console.log(form);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function()
{ try
{
jQuery(io).remove();
jQuery(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if(form.encoding)
{
jQuery(form).attr('encoding', 'multipart/form-data');
}
else
{
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback );
return {abort: function () {}};
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
return data;
}
})
That is a typical Microsoft security measure (e.g. to stop automated uploads).
That means you have to originate an upload from an actual user-pressed button click.
Style the button to make it look like a link instead.

Ajax Json problems with Jquery in Firefox

I am experiencing some troubles using ajax in my jQuery call in order to produce a json response. Basically I am trying to get all the images in a specific directory. Below is my jQuery code, and this works fine for directories with less than about 50 images, but once the number of images is greater than that, Firefox will just abort the request. This works fine in Safari, Chrome, IE. Either they are doing something wrong and Firefox is doing it right, and I am making an error, or this is one of the rare times when Firefox is the culprit. I have tried $.getJSON and disabling caching of the ajax requests, but that does not seem to work either. Any help will be greatly appreciated and thanks in advance.
var activeRequest = false;
var error = "The system could not read the directory at this time.";
var current = this.location['href'];
var filesCache = {};
function addFile(list, varToAdd, path, id){
if (typeof varToAdd != 'undefined' && varToAdd != null ){
var imagePath = path;
var srcPath = path+"/"+varToAdd['file'];
imagePath = "/cms/images/thumbs/"+imagePath+varToAdd['file'];
var filename = varToAdd['file'];
if(filename.length >18){
filename = filename.substr(0, 15)+"...";
}
var fileInfo = '<li id ="'+varToAdd['file'].replace('.', '')+'">';
fileInfo += '<a class = "thumb" href="'+srcPath+'" target="_blank"><img src="'+srcPath+'" width="'+varToAdd['width']+'" height="'+varToAdd['height']+'" alt="'+varToAdd['file']+'" /></a>';
fileInfo += '<ul class="fileInfo"><li title="'+varToAdd['file']+'">'+filename+'</li><li>'+varToAdd['dims']+'px</li><li>'+varToAdd['size']+'kb</li></ul>';
fileInfo += '</li>';
list.append(fileInfo);
delete fileInfo;
}
else
return false;
}
function lookupFiles(path){
var cleanPath = decodeURIComponent(path);
cleanPath += "/";
var urlLookUp = '/cms/images/lookup/file/?path='+encodeURIComponent(cleanPath);
var loader = $(".folder-contents .header");
$.ajaxSetup({
cache: false
});
var ajaxRequest = $.ajax({
type: 'GET',
url: urlLookUp,
data: path,
dataType: 'json',
beforeSend: function (request) {
if(!activeRequest)
loader.addClass('loading');
else
return false;
},
error: function(XMLHttpRequest, textStatus, errorThrown){
loader.addClass('error').removeClass('loading');
alert(error);
},
success: function(response, status, XMLHttpRequest) {
list = $(".folder-contents > ul.files");
if(typeof response != 'undefined' && response != null){
if(status == 'success' && (typeof response.files != 'undefined' && response.count > 0)){
list.empty();
$.each((response.files), function(index, value) {
addFile(list, value, path, response.searchTerm);
});
//list.append('</ul>');
}
else if (status == 'success' && (typeof response.files != 'undefined' && response.count == 0)){
list.empty();
list.append('<li class = "noresults">There are no images in this folder</li>');
}
else{
formLabel.addClass('error').removeClass('loading');
alert('Error');
}
}
loader.removeClass('loading');
}
});
/*
var json = $.getJSON( urlLookUp+"format=json&jsoncallback=?", function ( data ) {
console.log( data );
} );
*/
}
$(document).ready(function() {
$("a.directory").live('click',function(ev){
ev.preventDefault();
if($(this).hasClass('open')){
$(this).addClass('empty').removeClass('open').html('-');
lookup($(this).attr("title"));
}
else if($(this).hasClass('close')){
$(this).addClass('open').removeClass('close').html('+');
$(this).parent().find('ul').remove();
}
});
$("a.folder").live('click',function(ev){
ev.preventDefault();
lookupFiles($(this).attr("title"));
});
$(".files li").live('click', function(ev){
ev.preventDefault();
// send ckeditor back what image was selected - url from jquery selector & callBack from the view
var fileUrl = $(this).find('a').attr("href");
var callBack = window.CKEditorFuncName;
window.opener.CKEDITOR.tools.callFunction(callBack, fileUrl);
window.close();
});
});

Categories