Products

Solutions

Resources

Partners

Community

Blog

About

QA

Ideas Test

New Community Website

Ordinarily, you'd be at the right spot, but we've recently launched a brand new community website... For the community, by the community.

Yay... Take Me to the Community!

Welcome to the DNN Community Forums, your preferred source of online community support for all things related to DNN.
In order to participate you must be a registered DNNizen

HomeHomeDevelopment and...Development and...Building ExtensionsBuilding ExtensionsModulesModulesuploading a file to a  Dnn Api using ajaxuploading a file to a Dnn Api using ajax
Previous
 
Next
New Post
11/12/2014 8:26 AM
 

Hello, 

I am developing a module and want to be able to send a file + some other information to a API that inherits from DnnApiController.  

I just want to send one file at the time and get it in the api. 

So far I made :

public class FileController : DnnApiController
    {
        [AllowAnonymous]
        [HttpPost]
        public HttpResponseMessage Upload(string fileName)
        {
            HttpContextBase context = HttpContextSource.Current;
            for (var i = 0; i < context.Request.Files.Count; i++)
            {
                var file = context.Request.Files[i];
....



But It seems like  HttpContextSource.Current  has no file. 

Can somebody please give me a JQuey + C# code that works and can upload and get one file to such API ?  

I checked source code FileUploadController and filepicker but not really helped.   
 
New Post
11/12/2014 8:15 PM
 

It has been some time since I messed with this code -- it was a personal project that I haven't been back to for awhile and not at all refined, but I just tested it again and it is working.

//JS//

I'm using drag and drop in the UI so in my drop event I have:

var files = e.originalEvent.dataTransfer.files;
instance._uploadFile(files[0]);

And then:

_uploadFile: function (file) {
	var instance = this;
	var xhr = new XMLHttpRequest();

	if (xhr.upload && file.size <= instance.options.maxFileSize) {

		xhr.upload.addEventListener("progress", function (e) {
			var progress = parseInt(100 - (e.loaded / e.total * 100));
			instance.element.find('.progress').css({ width: progress + '%' }).show();
		}, false);

		xhr.onreadystatechange = function (e) {
			if (xhr.readyState == 4) {
				instance.element.find('.progress').addClass((xhr.status == 200 ? "success" : "failure"));
			}
		};

		var S = $.ServicesFramework(instance.options.moduleId);

		var url = S.getServiceRoot('VoxDynamic.OM') + "/AudioFile/Upload";

		var formData = new FormData();
		formData.append("file", file);

		xhr.open("POST", url, true);                
		xhr.setRequestHeader("X_PORTALID", instance.options.portalId);                
		xhr.send(formData);
	}
}

//AudioFileController.cs//

And for the web service:

public class AudioFileController : DnnApiController
{
	[AllowAnonymous]
	[HttpPost]
	[ValidateAntiForgeryToken]
	public async Task<HttpResponseMessage> Upload()
	{
		var portalId = Convert.ToInt32(Request.Headers.Where(x=> x.Key == "X_PORTALID").Single().Value.First());

		if (!Request.Content.IsMimeMultipartContent())
		{
			throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
		}

		var provider = new FilteredMultipartMemoryStreamProvider(new string[] { "mp3" });

		await Request.Content.ReadAsMultipartAsync(provider);

		if (provider.Contents.Count > 0)
		{
			var content = provider.Contents.Single();
			var stream = await content.ReadAsStreamAsync();
			IFileInfo tempFile;

			if (!FolderManager.Instance.FolderExists(portalId, "Audio"))
			{
				CreateAudioFolder(portalId);
			}

			var audioFolder = FolderManager.Instance.GetFolder(portalId, "Audio");

			if (stream.Length != 0)
			{
				tempFile = FileManager.Instance.AddFile(audioFolder, Guid.NewGuid().ToString() + ".mp3", stream);
				return Request.CreateResponse(HttpStatusCode.OK, tempFile.FileId);
			}
		}

		throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType, "Count < 1"));

	}	
}

public class FilteredMultipartMemoryStreamProvider : MultipartMemoryStreamProvider
{
	private string[] _extensions;

	public FilteredMultipartMemoryStreamProvider(string[] extensions)
	{
		_extensions = extensions;
	}

	public override System.IO.Stream GetStream(HttpContent parent, System.Net.Http.Headers.HttpContentHeaders headers)
	{
		var filename = headers.ContentDisposition.FileName.Replace("\"", string.Empty);

		if (filename.IndexOf('.') < 0)
			return Stream.Null;

		var extension = filename.Split('.').Last();

		return _extensions.Any(i => i.Equals(extension, StringComparison.InvariantCultureIgnoreCase))
				   ? base.GetStream(parent, headers)
				   : Stream.Null;

	}
}
 
New Post
11/15/2014 7:25 AM
 
Thanks Brian!
It was a great help :)
 
New Post
11/15/2014 7:25 AM
 
Thanks Brian!
It was a great help :)
 
Previous
 
Next
HomeHomeDevelopment and...Development and...Building ExtensionsBuilding ExtensionsModulesModulesuploading a file to a  Dnn Api using ajaxuploading a file to a Dnn Api using ajax


These Forums are dedicated to discussion of DNN Platform and Evoq Solutions.

For the benefit of the community and to protect the integrity of the ecosystem, please observe the following posting guidelines:

  1. No Advertising. This includes promotion of commercial and non-commercial products or services which are not directly related to DNN.
  2. No vendor trolling / poaching. If someone posts about a vendor issue, allow the vendor or other customers to respond. Any post that looks like trolling / poaching will be removed.
  3. Discussion or promotion of DNN Platform product releases under a different brand name are strictly prohibited.
  4. No Flaming or Trolling.
  5. No Profanity, Racism, or Prejudice.
  6. Site Moderators have the final word on approving / removing a thread or post or comment.
  7. English language posting only, please.
What is Liquid Content?
Find Out
What is Liquid Content?
Find Out
What is Liquid Content?
Find Out