1

I know how to upload a file and save it on the server as a physical file. I have successfully implemented this solution, there are lots of examples on the net.

Now I am searching for uploading a file and save it in a sql server database. Is it a totally different approach? I cannot find some examples on the net for this.

Any blogs/examples for a concrete implementation is welcome.

Thanks.

Below is my actual solution for uploading and saving a file on disk on the server (I am using the MultipartFormDataStreamProvider):

    [HttpPost]
    public Task<HttpResponseMessage> Post()
    {
        string RootPath = HttpContext.Current.Server.MapPath("~/" + RootFolder);

        if (Request.Content.IsMimeMultipartContent())
        {
            var streamProvider = new CustomMultipartFormDataStreamProvider(RootPath);
            var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<HttpResponseMessage>(t =>
            {
                if (t.IsFaulted || t.IsCanceled)
                {
                    throw new HttpResponseException(HttpStatusCode.InternalServerError);
                }

                // Move the file to the right destination depending on the type (defined client side)                    
                string type = streamProvider.FormData.GetValues("type").FirstOrDefault();
                string fullname = streamProvider.FormData.GetValues("fullname").FirstOrDefault();
                FileType fileType;

                if (!Enum.TryParse<FileType>(type, out fileType))
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "The file type is incorrect"));
                }

                var DestPath = RootPath + "\\" + GetFolderName(fileType);  

                if (!Directory.Exists(DestPath))
                    Directory.CreateDirectory(DestPath);

                var fileInfo = streamProvider.FileData.Select(i =>
                {
                    var info = new FileInfo(i.LocalFileName);
                    var fileName = fullname + info.Extension;
                    var srcFile = RootPath + "\\" + info.Name;
                    var dstFile = DestPath + "\\" + fileName;                        
                    var filesize = info.Length;

                    switch (fileType)
                    {
                        case FileType.DriverCertificate:
                            if (File.Exists(dstFile))
                                File.Delete(dstFile);
                            File.Move(srcFile, dstFile);
                            break;
                        default:
                            break;
                    }
                    return new FileDescription(fileName, DriverCertificatesFolder + "/" + fileName, filesize / 1024);
                });
                return new HttpResponseMessage()
                {
                    Content = new JsonContent(new
                    {
                        Success = true, 
                        Data = fileInfo 
                    })
                };
                ;
            });

            return task;
        }
        else
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
        }

    }
Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
Bronzato
  • 9,438
  • 29
  • 120
  • 212
  • You can take a look at my answer here:http://stackoverflow.com/questions/15842496/is-it-possible-to-override-multipartformdatastreamprovider-so-that-is-doesnt-sa/15843410#15843410...Here instead of the AWS stream, you could instead stream to a database. – Kiran Jul 02 '13 at 14:11

1 Answers1

0

This now really becomes a sql server question.

You need to store the binary data in a varbinary(max) column. More help here.

Community
  • 1
  • 1
Aliostad
  • 80,612
  • 21
  • 160
  • 208
  • 2
    Before this becomes a SQL question this is a perfectly valid ASP.NET WEB API question: `How do you get the uploaded file into a stream without saving it to the file system?`. Once you get this stream your answer about storing it in SQL applies. So what about the first part of this question which IMHO is more important here because the second part, as you already stated, has more than enough resources on the internet. – Darin Dimitrov Jul 02 '13 at 13:26
  • @DarinDimitrov where OP asks for "without saving it to the file system"? – Aliostad Jul 02 '13 at 13:58
  • Yes, that's exactly what he is asking. He even showed a code in which he is already saving the file to the file system so we could assume that he knows how to do that. – Darin Dimitrov Jul 02 '13 at 14:15
  • Yes I know how to proceed to save an uploaded file on the disk but I need guidance on the save the uploaded file directly in the database (without saving it on the file system). It seems we can avoid using `MultipartFormDataStreamProvider` and preferably use `MultipartMemoryStreamProvider` which avoid using files, correct? Thanks anyway. – Bronzato Jul 02 '13 at 14:23
  • Yes, this is correct but a bad approach as the `MultipartMemoryStreamProvider`, as it name suggests, loads the uploaded files in memory which could be catastrophic to your application. You'd better write a custom `MultipartStreamProvider` that will handle this for you. – Darin Dimitrov Jul 02 '13 at 14:51