Метод в модуле DNN возвращает нулевое значение при попытке асинхронно загрузить файл через JQuery Ajax и сохранить его в папке - PullRequest
1 голос
/ 26 июня 2019

Я получаю нулевое свойство в файле UploadController.cs, который находится в моем модуле DotNetNuke.

enter image description here

Я пытаюсь загрузить файлиспользование Ajax JQuery с использованием контроллера загрузки и сохранение файла для зарегистрированного пользователя DNN.

Вот мой элемент управления загрузкой:

<p>Select a file:</p>
<asp:FileUpload CssClass="fileuploadcss" ClientIDMode="Static" ID="upload_control" runat="server" />
<button ID="upload_button" class="upload_btn">Upload</button>

Вот код JQuery Ajax:

$('.upload_btn').on("click", function (e) {
    e.preventDefault();

    if ($("#upload_control")[0].files.length === 0) {
        $.fancybox.open("<div class='nofileselected'><h2>No File Selected</h2><p>No file has been selected to upload.</p></div>");
    } else {
        var _URL = window.URL || window.webkitURL;
        var file, img;
            if ((file = $('#upload_control')[0].files[0])) {
                img = new Image();
                img.onload = function () {
                    sendFile(file);
                };
                img.onerror = function () {
                    alert("Not a valid file:" + file.type);
                };
                img.src = _URL.createObjectURL(file);
            }

        function sendFile(file) {
            var formData = new FormData();
            formData.append('file', $('#upload_control')[0].files[0]);
            $.ajax({
                type: 'GET',
                async: true,
                url: $.fn.GetBaseURL() + 'DesktopModules/ProductDetailedView/API/Upload/ProcessRequest',
                data: JSON.stringify({context: formData}),
                success: function (status) {
                    if (status != 'error') {
                        console.log("Sucess");
                    }
                },
                processData: false,
                contentType: false,
                error: function () {
                    alert("Something went wrong!");
                }
            });
        }
} 
});

Я получаю ошибку 500, когда делаю POST вместо GET в DNN?

Вот код для моего файла RouteMapper.cs:

using DotNetNuke.Web.Api;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Http.WebHost;
using System.Web.Routing;
using System.Web.SessionState;

namespace Prod.Modules.ProductDetailedView.Services
{
/// <summary>
/// Maps the Api Routes for this Module.
/// </summary>
public class RouteMapper : IServiceRouteMapper
{
    private const string conModuleFolder = "ProductDetailedView";
    private const string conNamespace = "Prod.Modules.ProductDetailedView.Services";

    public void RegisterRoutes(IMapRoute mapRouteManager)
    {
        var apiRoutes = mapRouteManager.MapHttpRoute(conModuleFolder, "default", "{controller}/{action}", new[] { conNamespace }).ToArray();
        var uploadImageRoute = apiRoutes.Where(r => r.GetName() == "UploadController").FirstOrDefault();
    }
}
}

Здеськод UploadController, который получает ошибку:

using DotNetNuke.Entities.Portals;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Web.Api;
using System;
using System.IO;
using System.Web.Http;
using DotNetNuke.Services.Log.EventLog;
using DotNetNuke.Services.Exceptions;
using System.Text;
using System.Web;

namespace Prod.Modules.ProductDetailedView.Services
{
/// <summary>
/// DNN Web API Controller
/// </summary>
public class UploadController : DnnApiController
{
    [AllowAnonymous]
    [HttpPost]
    [HttpGet]
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        try
        {
            string dirFullPath = 
            HttpContext.Current.Server.MapPath("~/MediaUploader/");
            string[] files;
            int numFiles;
            files = System.IO.Directory.GetFiles(dirFullPath);
            numFiles = files.Length;
            numFiles = numFiles + 1;
            string str_image = "";

            foreach (string s in context.Request.Files)
            {
                HttpPostedFile file = context.Request.Files[s];
                string fileName = file.FileName;
                string fileExtension = file.ContentType;

                if (!string.IsNullOrEmpty(fileName))
                {
                    fileExtension = Path.GetExtension(fileName);
                    str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
                    string pathToSave_100 = HttpContext.Current.Server.MapPath("~/MediaUploader/") + str_image;
                    file.SaveAs(pathToSave_100);
                }
            }
            //  database record update logic here  ()

            context.Response.Write(str_image);
        }
        catch (Exception ac)
        {

        }
    }
   }
  }

Можно ли использовать HttpContext в отдельном файле контроллера в DNN?

Это структура в VS:

enter image description here

...