Click here to Skip to main content
15,886,857 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have two projects; First one is a asp.net web project and the second one is embedded http server library project.

Embedded http server project is taken from : embedded http server project

I want to save a video file from user's local to user's shared storage. I'm getting and sending file from browser using ajax request. Embedded http server is supposed to get bytearray and save video on client's shared storage. I have a problem that I spent days to solve but not yet found a solution.

In chrome it stucks on stream.CopyTo(streamReader);

In firefox and IE it gives "Cross-Origin Request Blocked" error but firefox saves file even it gives the error.

Here is the ajax request code;

JavaScript
$(document).ready(function () {

          function hashFile(file, chunkSize, callback) {
            var size = file.size;
            var offset = 0;
            var chunk = file.slice(offset, offset + chunkSize);

			SendChunk(chunk,0);
			
            var hashChunk = function () {
                var reader = new FileReader();
                reader.onload = function (e) {
                    
                    offset += chunkSize;

                    if (offset < size) {
                        chunk = file.slice(offset, offset + chunkSize);

						SendChunk(chunk,0);
                    } 
					else if (offset > size){
						offset -= chunkSize;
						var newchunkSize = size - offset;
						
						chunk = file.slice(offset, offset + newchunkSize);

						SendChunk(chunk,1);
                    }
                };

                reader.readAsArrayBuffer(chunk);
            };

			function SendChunk(chunk,end){
				
				if(end>0)
				{
					 var ajaxRequest = $.ajax({
						type: "POST",
						url: "http://clientip:8080/savefileend",
						contentType: false,
						processData: false,
						data: chunk
					});
				}
				else{
					var ajaxRequest = $.ajax({
						type: "POST",
						url: "http://clientip:8080/savefile",
						contentType: false,
						processData: false,
						data: chunk
					});
					
					ajaxRequest.done(function (e) {
						hashChunk();
					
					});
					ajaxRequest.error(function (xhr) {
						console.log(e);
						hashChunk();
					});
				}
			}
        }

        function fileInputHandler(evt) {
            var files = evt.target.files;
            var chunkSize = 10485760; // bytes
            var start = window.performance ? performance.now() : Date.now(); // DEBUG
            var onHashFile = function (digest) {
                var end = window.performance ? performance.now() : Date.now(); // DEBUG
                console.log(this.name, digest, (end - start) + 'ms'); // DEBUG
            };
            for (var i = 0, len = files.length; i < len; i++) {
                hashFile(files[i], chunkSize, onHashFile);
            }
        }

        document.getElementById('file1')
  .addEventListener('change', fileInputHandler, false);
});


and here is the embedded server code to get the request;

C#
var stream = request.GetRequestStream();

                    using (var streamReader = new MemoryStream())
                    {
                        stream.CopyTo(streamReader);
                        videoTemp = streamReader.ToArray();
                    }

                    using (var fileStream = new FileStream(path, FileMode.Append))
                    {
                        fileStream.Write(videoTemp, 0, videoTemp.Length);
                    }



CSS
By the way,

For IE: If I enabled "Access data sources across domains" from setting -security... then it works without error in IE.

For Chrome: If I start chrome with --disable-web-security parameter it works without error in chrome.

But I have find the solution from code.

Need suggestions urgently..
Posted
Updated 29-Apr-20 1:26am
v2
Comments
Sinisa Hajnal 3-Apr-15 5:04am    
You have to have your ajax page and your origin page should have the same domain.
for example, if your site is www.example.com your ajax should have www.example.com/something

You could also try setting ajax dataType to jsonp (you'll have to google the details this is from memory).
kubibay 3-Apr-15 5:35am    
They are not on the same server, web project will be on web server (in this case on a virtual pc) and any client will have their own embedded http server to handle client responses, I know it sounds weird but I will save a video file from user's desktop to shared storage via the web project. I'm sending ajax request from client's browser and embedded http server will handle the request.
kubibay 3-Apr-15 7:57am    
If I add this to the ajax request; beforeSend: function (request) { request.setRequestHeader("Access-Control-Allow-Origin", "*"); request.setRequestHeader("Access-Control-Allow-Headers", "Content-Type"); } then debug stops on stream.CopyTo(streamReader); if I close web page it goes on but this time streamreader is empty, If I stop the http server then it gives same error...!
F-ES Sitecore 3-Apr-15 8:56am    
It's the server that needs to return the "Access-Control-Allow-Origin" header.
csharpbd 3-Apr-15 10:51am    
Please read this: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Maybe it can help you.

1) Try to move both client and server apps on same machine (for testing). If they work fine, then its a CORS issue only.
If WebAPI code, set the EnableCors attribute with the wildcard on client's address (unless you have specific ones). You can either set this on specific methods or on entire site.

However it seems the error is something else since you are getting blocked on setting the headers in Chrome.
2) Try to transfer a small file (few kb) with the current settings to see if it works. If it does get copied, then your network buffer has been set too low for you target video files. All browsers have their file transfer limit so you need to increase this. See ASP.NET Max Request Length
 
Share this answer
 
CSS
I have found the solution, if anyone needs it;
I have used http://nancyfx.org/ 
Nancy.Hosting.Self library for embedded http server, Here I was able to add "Access-Control-Allow-Origin" to response.Headers so that I could transfer file without error.
 
Share this answer
 
1) Install this nuget package in your solution
Install-Package Microsoft.AspNet.WebApi.Cors >> latest version
2) your controller should be
namespace test
{
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class TestController : ApiController
{
// your code
}
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900