Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error to upload file to server #214

Open
danielcuautle opened this issue Dec 7, 2018 · 3 comments
Open

Error to upload file to server #214

danielcuautle opened this issue Dec 7, 2018 · 3 comments

Comments

@danielcuautle
Copy link

I'm try to upload file to server, but the browser console write this:

SimpleAjaxUploader.js:1828 POST ..../SaveFiles.asmx/Save 500 (Internal Server Error)
_uploadXhr @ SimpleAjaxUploader.js:1828
_initUpload @ SimpleAjaxUploader.js:1882
submit @ SimpleAjaxUploader.js:1160
(anonymous) @ SimpleAjaxUploader.js:2046

@markusramsak
Copy link

Is your server url correct?
If yes, then your server side code might produce some error. Try to simplify your code, so you can locate the source of the error for specific.

@LPology
Copy link
Owner

LPology commented Dec 12, 2018

Can you post the server side code for handling the upload and the Javascript code you're using?

@danielcuautle
Copy link
Author

CLIENT:
<script>
function escapeTags(str) {
return String(str)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '<').replace(/>/g, '>');
}

                        window.onload = function () {

                            try {
                                var idbtn = document.getElementById('uploadBtn'),
                                    progressBar = document.getElementById('progressBar'),
                                    progressOuter = document.getElementById('progressOuter'),
                                    msgBox = document.getElementById('msgBox');

                                var uploader = new ss.SimpleUpload({
                                    button: idbtn,
                                    url: 'SaveFiles.asmx/Save',
                                    name: 'uploadfile',
                                    dropzone: 'zonadrag',
                                    dragClass: 'demo-droppable',
                                    allowedExtensions: ['jpg', 'png', 'pdf', 'svg'],
                                    multipart: true,
                                    hoverClass: 'hover',
                                    multiple: true,
                                    focusClass: 'focus',

                                    responseType: 'json',
                                    startXHR: function () {
                                        progressOuter.style.display = 'block';
                                        this.setProgressBar(progressBar);
                                    },

                                    onSubmit: function () {
                                        msgBox.innerHTML = '';
                                        idbtn.innerHTML = 'Cargando...';
                                    },

                                    onComplete: function (filename, response) {
                                        idbtn.innerHTML = 'Examinar';
                                        progressOuter.style.display = 'none';
                                        $('#btnGuardarAgregaExp').show();

                                        if (!response) {
                                            msgBox.innerHTML = 'Inactiva la carga del archivo';
                                            return;
                                        }

                                        if (response.success === true) {
                                            msgBox.style.display = 'block';
                                            msgBox.innerHTML = '<strong><a href="Recursos/' + escapeTags(filename) + '"> ' + escapeTags(filename) + '</strong> ' + 'Archivo cargado.';

                                            var output = document.getElementById('fileInput');
                                            output.innerHTML = '';

                                            if (response.typeFile === 'jpg' || response.typeFile === 'png' || response.typeFile === 'svg')
                                                output.innerHTML += `<img class="img-fluid" src="../../Recursos/temp/${response.folderName}/${response.fileName}" />`;

                                            if (response.typeFile === 'pdf')
                                                output.innerHTML += `<object id="visualizadorPDF" data="../../Recursos/temp/${response.folderName}/${response.fileName}" type="application/pdf" width="100%" height="500"></object>`;

                                            $('#txtTypeFile').val(response.typeFile);
                                            $('#txtFileName').val(response.fileName);
                                            $('#txtFolderName').val(response.folderName);
                                        } else {
                                            if (response.msg) {
                                                msgBox.innerHTML = escapeTags(response.msg);

                                            } else {
                                                msgBox.innerHTML = 'Hay un error en la carga del archivo.';
                                            }
                                        }
                                    },
                                    onError: function () {
                                        progressOuter.style.display = 'none';
                                        msgBox.innerHTML = 'Hay un error con el plugin';
                                    }
                                });
                            } catch (e) {
                                alert(e.message);
                            }
                        };
                    </script>

SERVER:

using RedRingQuiscoDB.Modelos.Seguridad;
using RedRingQuiscoDB.Utileria;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Script.Services;
using System.Web.Services;

namespace RedRingQuioscoWeb.Views.Home
{
///


/// Summary description for SaveFiles
///

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class SaveFiles : System.Web.Services.WebService
{

    [WebMethod(EnableSession = true)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void Save()
    {
        try
        {
            HttpContext Contexto = HttpContext.Current;
            HttpFileCollection vFilesCollection = Context.Request.Files;

            Usuario usuario = (Usuario)(HttpContext.Current.Session["Login_Usuario"]);
            string vPath = HostingEnvironment.MapPath($"~/Recursos/temp/{usuario.IdUsuario}");

            if (Directory.Exists(vPath))
            {
                string[] filePaths = Directory.GetFiles(vPath);
                foreach (string filePath in filePaths)
                    File.Delete(filePath);
            }

            string vNameFile = string.Empty;
            for (int x = 0; x < vFilesCollection.Count; x++)
            {
                vNameFile = vFilesCollection[x].FileName;
                string vFileInfo = System.IO.Path.GetFileName(vFilesCollection[x].FileName);
                string vFolderToSave = $"{Server.MapPath("Recursos")}\\{vFileInfo}";

                if (!Directory.Exists(vPath))
                {
                    Directory.CreateDirectory(vPath);
                }

                string[] words = vNameFile.Split('.');
                string vTypeFile = words[words.Length - 1];
                vFilesCollection[x].SaveAs($"{vPath}/{vFileInfo}");
                Contexto.Response.ContentType = "application/json";
                Contexto.Response.Write("{\"success\":true,\"msg\":\"" + vNameFile + "\",\"fileName\":\"" + vNameFile + "\",\"folderName\":\"" + usuario.IdUsuario + "\",\"typeFile\":\"" + vTypeFile + "\"}");
                Contexto.Response.End();
            }
        }
        catch (Exception ex)
        {
            Log.Instances.RegistroError(ex);
        }
    }
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants