Ну, этот код работает для меня на localhost, но когда я размещаю его на интернет-сервере, он не сохраняет загружаемый файл - PullRequest
0 голосов
/ 21 июня 2019

В этом коде я использую службу asmx с использованием ajax, мои файлы хранятся на локальном хосте, но когда я загружаю их на сервер в Интернете, они не сохраняются, я предоставляю им полные права доступа в IIS.и я до сих пор не нахожу проблемы.enter image description here

 var form_data = new FormData();

 form_data.append("Archivo", $('#txtArchivo')[0].files[0])
 form_data.append("Fecha", $("#txtTitulo").val())
 form_data.append("Descripcion", $("#txtActuaciones").val())
 form_data.append("Id", $("#txtRadicadoOculto").val())
 form_data.append("Carpeta", $("#inputSuccess").val())
 console.log("datos" + JSON.stringify(form_data))
 var param = {
              Id: $("#txtRadicadoOculto").val(),
              Fecha: $("#txtTitulo").val(),
              Descripcion: $("#txtActuaciones").val(),
              Archivo: form_data
              };
console.log("con el archivo" + JSON.stringify(param));

//  formData.append("file", file);
$.ajax({
        url: '<%=ResolveUrl("ArchivoActuacion.asmx/Guardar")%>',
        type: 'POST',
        data: form_data,
        // cache: false,
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        beforeSend: function () {
            $("#load").fadeIn(100);
            $('#loading').css({
                'display': 'block'
            });
        },
        success: function (data) {
            console.log("mi respuesta" + data.success)
            $("#load").fadeOut(200);
            if (data.success != true) {
                alert("No pudo guardarse! " + data.success)
            } else {
                alert("Guardado Satisfactoriamente!")
                $("#txtTitulo").val("")
                $("#txtActuaciones").val("")
                $('#txtArchivo').val("");
            }

            //alert("Guardado satisfactoriamente")
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
                   var err = eval("(" + XMLHttpRequest.responseText + ")");
                   alert("ojo" + err.Message)
                   console.log("Ajax Error!");
                   $("#load").fadeOut(200);
               }
           });

этот код находится в c #

публичном классе ArchivoActuacion: System.Web.Services.WebService {

public ArchivoActuacion()
{

    //Elimine la marca de comentario de la línea siguiente si utiliza los componentes diseñados 
    //InitializeComponent(); 
}

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void Guardar()
{
    HttpContext Contexto = HttpContext.Current;

    string radicado = Contexto.Request.Form["Id"];
    // Byte[] archi = Contexto.Request.Form["archivo"]
    string fecha = Contexto.Request.Form["Fecha"];
    string descripcion = Contexto.Request.Form["Descripcion"];
    string carpeta = Contexto.Request.Form["Carpeta"];
    HttpFileCollection ColeccionArchivos = Context.Request.Files;


    string NombreArchivo = "";
    string directorio = "";
    int ArchivoActual = 0;

    SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConLegasis"].ConnectionString);


    if (ColeccionArchivos.Count != 0)
    {

        Contexto.Server.ScriptTimeout = 2400;
        NombreArchivo = ColeccionArchivos[0].FileName;
        String DatosArchivo = System.IO.Path.GetFileName(ColeccionArchivos[0].FileName);
        string filename = string.Format("{0}{1:yyyyMMdd_HHmmss}.{2}", Path.GetFileNameWithoutExtension(ColeccionArchivos[ArchivoActual].FileName), DateTime.Now, Path.GetExtension(ColeccionArchivos[ArchivoActual].FileName));
        string cadena = filename.Replace(" ", String.Empty);
        // hpf.SaveAs(Server.MapPath(txtId.Value + "\\") + Path.GetFileName(cadena));
        if (Directory.Exists(Server.MapPath(carpeta)))
        {
            // String CarpetaParaGuardar = Server.MapPath("files") + "\\" + cadena;
            String CarpetaParaGuardar = Server.MapPath(carpeta + "\\") + Path.GetFileName(cadena);
            ColeccionArchivos[0].SaveAs(CarpetaParaGuardar);
            directorio = "./" + carpeta + "/" + Path.GetFileName(cadena);// para sql
            var strSQL = "INSERT INTO Actuacion_simple VALUES(" + radicado + ",'" + fecha + "', '" + descripcion.ToUpper().ToString() + "','" + directorio + "')";
            var cmd = new SqlCommand(strSQL, cn);
            cn.Open();
            cmd.ExecuteNonQuery();
            cn.Close();
            Contexto.Response.ContentType = "application/json";
            Contexto.Response.Write("{\"success\":true,\"msg\":\"" + NombreArchivo + "\"}");
            Contexto.Response.End();

        }
     else
    {
            Directory.CreateDirectory(Server.MapPath(carpeta));
            String CarpetaParaGuardar = Server.MapPath(carpeta + "\\") + Path.GetFileName(cadena);
            ColeccionArchivos[0].SaveAs(CarpetaParaGuardar);
            directorio = "./" + carpeta + "/" + Path.GetFileName(cadena);// para sql
            var strSQL = "INSERT INTO Actuacion_simple VALUES(" + radicado + ",'" + fecha + "', '" + descripcion.ToUpper().ToString() + "','" + directorio + "')";
            var cmd = new SqlCommand(strSQL, cn);
            cn.Open();
            cmd.ExecuteNonQuery();
            cn.Close();
            Contexto.Response.ContentType = "application/json";
            Contexto.Response.Write("{\"success\":true,\"msg\":\"" + NombreArchivo + "\"}");
            Contexto.Response.End();
        }
}
    else
    {
        directorio = "";
        var strSQL = "INSERT INTO Actuacion_simple VALUES(" + radicado + ",'" + fecha + "', '" + descripcion.ToUpper().ToString() + "','" + directorio + "')";
        var cmd = new SqlCommand(strSQL, cn);
        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
        Contexto.Response.ContentType = "application/json";
        Contexto.Response.Write("{\"success\":true,\"msg\":\"" + NombreArchivo + "\"}");
        Contexto.Response.End();
    }




}

}

...