Software Archive
Read-only legacy content
17060 Discussions

Upload files to a asp.net webservice

Rodrigo_M_1
New Contributor II
2,853 Views

Hello everyone,

I'm trying to upload a file through asp.net webservice but I'm not able to make it work...

Here is the code of my asp.Net Webservice in C#:

using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.IO;


namespace Uploader
{
    /// <summary>
    /// This web method will provide an web method to load any
    /// file onto the server; the UploadFile web method
    /// will accept the report and store it in the local file system.
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    public class FileUploader : System.Web.Services.WebService
    {

        [WebMethod]
        public string UploadFile(byte[] f, string fileName)
        {
            // the byte array argument contains the content of the file
            // the string argument contains the name and extension
            // of the file passed in the byte array
            try
            {
                // instance a memory stream and pass the
                // byte array to its constructor
                MemoryStream ms = new MemoryStream(f);

                // instance a filestream pointing to the 
                // storage folder, use the original file name
                // to name the resulting file
                FileStream fs = new FileStream
                    (System.Web.Hosting.HostingEnvironment.MapPath("~/TransientStorage/") + 
                    fileName, FileMode.Create);

                // write the memory stream containing the original
                // file as a byte array to the filestream
                ms.WriteTo(fs);

                // clean up
                ms.Close();
                fs.Close();
                fs.Dispose();

                // return OK if we made it this far
                return "OK";
            }
            catch (Exception ex)
            {
                // return the error message if the operation fails
                return ex.Message.ToString();
            }
        }
    }
}

 

Do anyone have some sample working code for Intel XDK to work with this webservice ?

I'm not posting my code here to don't make any conflict because it's a big mess I have tried a lot of codes...

Thanks!

0 Kudos
1 Solution
Nick_F_2
New Contributor III
2,853 Views

Try this, it handles images and video, I also use the NRECO video tools to create video thumbnails and image manipulation during the upload.

<WebMethod()> _
    Public Function SaveFiles() As String
        Try
            Dim FileCount As Integer = 0
            FileCount = HttpContext.Current.Request.Files.Count
            For i As Integer = 0 To FileCount - 1
                myfile = HttpContext.Current.Request.Files(i)
                FileName = HttpContext.Current.Request.Files(i).FileName
                If FileName.EndsWith(".jpg") Then
                    FileName += ".jpg"
                End If
                If FileName.EndsWith(".mov") Then
                    FileName += ".mov"
                End If
                If FileName.EndsWith(".mp4") Then
                    FileName += ".mp4"
                End If
                Dim parameters As NameValueCollection = HttpContext.Current.Request.Params
                Dim newfileparam() As String = parameters.GetValues("newfile")
                newfilename += newfileparam(0).ToString
                Dim newpathparam() As String = parameters.GetValues("projpath")
                newfilepath += newpathparam(0).ToString
                Dim Rotation() As String = parameters.GetValues("rotation")
                Rot = Rotation(0)
                writefile("Rotation=" & Rot)
                If (Not Directory.Exists(newfilepath)) Then
                    Directory.CreateDirectory(newfilepath)
                End If
            Next
            newfileloc = Path.Combine(newfilepath, newfilename)
            writefile("File uploaded: " + newfileloc)
            myfile.SaveAs(newfileloc)
            If FileName.EndsWith(".mp4") Then
                Dim ffMpeg = New NReco.VideoConverter.FFMpegConverter()
                Dim ThumbFilename As String() = Split(FileName, ".")
                Dim newpath As String = newfilepath & "\" & ThumbFilename(0) & "_thm.jpg"
                ffMpeg.GetVideoThumbnail(newfileloc, newpath, 1)
                writefile("Video Thumbnail Created: " + newpath)
                Dim RotThumb As Image = System.Drawing.Image.FromFile(newpath)
                If Rot = 90 Then
                    RotThumb.RotateFlip(RotateFlipType.Rotate90FlipXY)
                End If
                If Rot = 180 Then
                    RotThumb.RotateFlip(RotateFlipType.Rotate180FlipXY)
                End If
                If Rot = 270 Then
                    RotThumb.RotateFlip(RotateFlipType.Rotate270FlipXY)
                End If
                RotThumb.Save(newpath, ImageFormat.Jpeg)
                RotThumb.Dispose()
                'writefile("Thumbnail Rotated: " + newpath)
            End If
            If FileName.EndsWith(".jpg") Then
                Dim RotImage As Image = System.Drawing.Image.FromFile(newfileloc)
                If Rot = 90 Then
                    RotImage.RotateFlip(RotateFlipType.Rotate90FlipXY)
                End If
                If Rot = 180 Then
                    RotImage.RotateFlip(RotateFlipType.Rotate180FlipXY)
                End If
                If Rot = 270 Then
                    RotImage.RotateFlip(RotateFlipType.Rotate270FlipXY)
                End If
                RotImage.Save(newfileloc, ImageFormat.Jpeg)
                RotImage.Dispose()
                Dim ThumbImageName As String = Path.GetFileNameWithoutExtension(newfileloc)
                Dim ThumbPath As String = Path.GetDirectoryName(newfileloc) & "\" & Path.GetFileNameWithoutExtension(newfileloc) & "_thm.jpg"
                CreateThumbnail(newfileloc, ThumbPath)
            End If
            Return "success"
        Catch ex As Exception
            writefile("****Error: " + ex.Message.ToString + "****")
            Return "fail"
        End Try
    End Function

And the Javascript uses phonrgap/cordova file transfer plugin.

function doUploadPics(){
   
    
    // upload pics
   var upStatus = document.getElementById("upStatus");
    upStatus.innerHTML = 'Status: Uploading Photos';
    document.getElementById('uploaderImage').src = "./styles/images/uploadpics.png";
    gvUploadfile = 0;
    gvUploadTotal = 0;
    var fType = 'file';
 
    
    var ft = new FileTransfer();
         ft.onprogress = function(progressEvent) {
            if (progressEvent.lengthComputable) {
                var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100);
                //alert("Uploading " + params.newfile + " " + perc + "% loaded...");
                if(perc <100) {
                    upStatus.innerHTML = "Uploading " + fType +" ( "  + perc + "% loaded )";
                    document.getElementById('uploaderImage').src = "./styles/images/uploadpics.png";
               
                 } else { 
                          upStatus.innerHTML = 'Status: Busy... ' ;
                        document.getElementById('uploaderImage').src = "./styles/images/eggtimer.png";
                 }
                
                
            } else {
                upStatus.innerHTML = "Uploading " + params.newfile +  "...";
            }
         }
    // upload photos
  
     for (i=1;i<=gvNumpics;i++){
        // fType = 'Photo';
         gvUploadfile += 1;
      
         // alert('uploading ' + gvUploadfile);
        var options = new FileUploadOptions();
        options.fileKey="file";
        options.fileName = 'pic' + gvUploadfile +'.jpg';
        options.mimeType="image/jpeg";
 
        var params = {};
        params.newfile  = 'pic' + gvUploadfile +'.jpg';
        params.projpath = gvDataPath;
        params.rotation = 0;
         if(device.platform == 'iOS') {
             params.rotation = 270;
         }
       
        
        //alert(params.projpath);
        options.params = params;
   
        
    
        ft.upload( encodeURI(picPaths), encodeURI("http://myURL/service.asmx/SaveFiles"), ftpwin, ftpfail, options);
  
     }
 
    // video uploads
    upStatus.innerHTML = 'Status: Uploading Videos';
    gvUploadfile = 0;
   
    for (i=1;i<=gvNumvids;i++){
        // fType = 'Video';
         gvUploadfile += 1;
       
         // alert('uploading ' + gvUploadfile);
        var options = new FileUploadOptions();
        options.fileKey="file";
        options.fileName = 'vid' + gvUploadfile +'.mp4';
        options.mimeType="video/*";
 
        var params = {};
        params.newfile  = 'vid' + gvUploadfile +'.mp4';
        params.projpath = gvDataPath;
        //alert(params.projpath);
         params.rotation = 0;
         if(device.platform == 'iOS') {
             params.rotation = 270;
         }
        options.params = params;
       
    //alert('callining upload video');
       // ft = new FileTransfer();
       
        ft.upload( encodeURI(vidPaths), encodeURI("http://myURL/service.asmx/SaveFiles"), ftpwin, ftpfail, options);
    //alert('called');
     }
   
   
    
    
}
 

 

View solution in original post

0 Kudos
5 Replies
Nick_F_2
New Contributor III
2,854 Views

Try this, it handles images and video, I also use the NRECO video tools to create video thumbnails and image manipulation during the upload.

<WebMethod()> _
    Public Function SaveFiles() As String
        Try
            Dim FileCount As Integer = 0
            FileCount = HttpContext.Current.Request.Files.Count
            For i As Integer = 0 To FileCount - 1
                myfile = HttpContext.Current.Request.Files(i)
                FileName = HttpContext.Current.Request.Files(i).FileName
                If FileName.EndsWith(".jpg") Then
                    FileName += ".jpg"
                End If
                If FileName.EndsWith(".mov") Then
                    FileName += ".mov"
                End If
                If FileName.EndsWith(".mp4") Then
                    FileName += ".mp4"
                End If
                Dim parameters As NameValueCollection = HttpContext.Current.Request.Params
                Dim newfileparam() As String = parameters.GetValues("newfile")
                newfilename += newfileparam(0).ToString
                Dim newpathparam() As String = parameters.GetValues("projpath")
                newfilepath += newpathparam(0).ToString
                Dim Rotation() As String = parameters.GetValues("rotation")
                Rot = Rotation(0)
                writefile("Rotation=" & Rot)
                If (Not Directory.Exists(newfilepath)) Then
                    Directory.CreateDirectory(newfilepath)
                End If
            Next
            newfileloc = Path.Combine(newfilepath, newfilename)
            writefile("File uploaded: " + newfileloc)
            myfile.SaveAs(newfileloc)
            If FileName.EndsWith(".mp4") Then
                Dim ffMpeg = New NReco.VideoConverter.FFMpegConverter()
                Dim ThumbFilename As String() = Split(FileName, ".")
                Dim newpath As String = newfilepath & "\" & ThumbFilename(0) & "_thm.jpg"
                ffMpeg.GetVideoThumbnail(newfileloc, newpath, 1)
                writefile("Video Thumbnail Created: " + newpath)
                Dim RotThumb As Image = System.Drawing.Image.FromFile(newpath)
                If Rot = 90 Then
                    RotThumb.RotateFlip(RotateFlipType.Rotate90FlipXY)
                End If
                If Rot = 180 Then
                    RotThumb.RotateFlip(RotateFlipType.Rotate180FlipXY)
                End If
                If Rot = 270 Then
                    RotThumb.RotateFlip(RotateFlipType.Rotate270FlipXY)
                End If
                RotThumb.Save(newpath, ImageFormat.Jpeg)
                RotThumb.Dispose()
                'writefile("Thumbnail Rotated: " + newpath)
            End If
            If FileName.EndsWith(".jpg") Then
                Dim RotImage As Image = System.Drawing.Image.FromFile(newfileloc)
                If Rot = 90 Then
                    RotImage.RotateFlip(RotateFlipType.Rotate90FlipXY)
                End If
                If Rot = 180 Then
                    RotImage.RotateFlip(RotateFlipType.Rotate180FlipXY)
                End If
                If Rot = 270 Then
                    RotImage.RotateFlip(RotateFlipType.Rotate270FlipXY)
                End If
                RotImage.Save(newfileloc, ImageFormat.Jpeg)
                RotImage.Dispose()
                Dim ThumbImageName As String = Path.GetFileNameWithoutExtension(newfileloc)
                Dim ThumbPath As String = Path.GetDirectoryName(newfileloc) & "\" & Path.GetFileNameWithoutExtension(newfileloc) & "_thm.jpg"
                CreateThumbnail(newfileloc, ThumbPath)
            End If
            Return "success"
        Catch ex As Exception
            writefile("****Error: " + ex.Message.ToString + "****")
            Return "fail"
        End Try
    End Function

And the Javascript uses phonrgap/cordova file transfer plugin.

function doUploadPics(){
   
    
    // upload pics
   var upStatus = document.getElementById("upStatus");
    upStatus.innerHTML = 'Status: Uploading Photos';
    document.getElementById('uploaderImage').src = "./styles/images/uploadpics.png";
    gvUploadfile = 0;
    gvUploadTotal = 0;
    var fType = 'file';
 
    
    var ft = new FileTransfer();
         ft.onprogress = function(progressEvent) {
            if (progressEvent.lengthComputable) {
                var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100);
                //alert("Uploading " + params.newfile + " " + perc + "% loaded...");
                if(perc <100) {
                    upStatus.innerHTML = "Uploading " + fType +" ( "  + perc + "% loaded )";
                    document.getElementById('uploaderImage').src = "./styles/images/uploadpics.png";
               
                 } else { 
                          upStatus.innerHTML = 'Status: Busy... ' ;
                        document.getElementById('uploaderImage').src = "./styles/images/eggtimer.png";
                 }
                
                
            } else {
                upStatus.innerHTML = "Uploading " + params.newfile +  "...";
            }
         }
    // upload photos
  
     for (i=1;i<=gvNumpics;i++){
        // fType = 'Photo';
         gvUploadfile += 1;
      
         // alert('uploading ' + gvUploadfile);
        var options = new FileUploadOptions();
        options.fileKey="file";
        options.fileName = 'pic' + gvUploadfile +'.jpg';
        options.mimeType="image/jpeg";
 
        var params = {};
        params.newfile  = 'pic' + gvUploadfile +'.jpg';
        params.projpath = gvDataPath;
        params.rotation = 0;
         if(device.platform == 'iOS') {
             params.rotation = 270;
         }
       
        
        //alert(params.projpath);
        options.params = params;
   
        
    
        ft.upload( encodeURI(picPaths), encodeURI("http://myURL/service.asmx/SaveFiles"), ftpwin, ftpfail, options);
  
     }
 
    // video uploads
    upStatus.innerHTML = 'Status: Uploading Videos';
    gvUploadfile = 0;
   
    for (i=1;i<=gvNumvids;i++){
        // fType = 'Video';
         gvUploadfile += 1;
       
         // alert('uploading ' + gvUploadfile);
        var options = new FileUploadOptions();
        options.fileKey="file";
        options.fileName = 'vid' + gvUploadfile +'.mp4';
        options.mimeType="video/*";
 
        var params = {};
        params.newfile  = 'vid' + gvUploadfile +'.mp4';
        params.projpath = gvDataPath;
        //alert(params.projpath);
         params.rotation = 0;
         if(device.platform == 'iOS') {
             params.rotation = 270;
         }
        options.params = params;
       
    //alert('callining upload video');
       // ft = new FileTransfer();
       
        ft.upload( encodeURI(vidPaths), encodeURI("http://myURL/service.asmx/SaveFiles"), ftpwin, ftpfail, options);
    //alert('called');
     }
   
   
    
    
}
 

 

0 Kudos
Rodrigo_M_1
New Contributor II
2,853 Views

All right Nick! Thanks for your help ! :)

0 Kudos
Nick_F_2
New Contributor III
2,853 Views

Are you downloading the plugin and installing locally or loading from the apache repos.

In XDK click on projects and Add Plugin to this project.

Select the Core Plugins File Transfer.

I have just done the same and the app compiled without an error.

0 Kudos
Rodrigo_M_1
New Contributor II
2,853 Views

Nick F. wrote:

Are you downloading the plugin and installing locally or loading from the apache repos.

In XDK click on projects and Add Plugin to this project.

Select the Core Plugins File Transfer.

I have just done the same and the app compiled without an error.

Now I got it ! I was trying to import, and just now I realize that it already comes with intel !

Could you share the HTML code also that I could try make it work ?

I'm trying to figure out the follow code:

 

ft.upload( encodeURI(picPaths), .....

and

 // upload pics
   var upStatus = document.getElementById("upStatus");
    upStatus.innerHTML = 'Status: Uploading Photos';

...

I could not understand the: "picPaths"

Thanks again!

0 Kudos
Nick_F_2
New Contributor III
2,853 Views

OK sorry, picPaths is a loop to upload multiple images. picPath is defined as the path to your image location.

In your HTML page you can have a label named "upStatus" and change the text to display a status message such as "Uploading Photos"

0 Kudos
Reply