简体   繁体   中英

Uploading files to server - c#

I build a client server application for uploading file from a client folder to server. My server WebMethod for uploading follows -

[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
    new general().logError("UploadFile " + fileName);
    try
    {
        // instance a memory stream and pass the
        // byte array to its constructor
        MemoryStream ms = new MemoryStream(f);

                   FileStream fs = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath
                    ("~/data/") + 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();
        new general().logError("After saving the file");
        // return OK if we made it this far
        return "OK";
    }
    catch (Exception ex)
    {

        return ex.Message.ToString();
    }
}

The function that calls this WebMethod follows -

private void uploadIt(string fName)
    {
        FileStream f = File.OpenRead(fName);

        cloudius.cloudius m = new cloudius.cloudius();

        using (MemoryStream ms = new MemoryStream())
        {
            f.CopyTo(ms);

            //string[] drive = fName.Split(':');
            string[] p = fName.Split('\\');

            string b = m.UploadFile(ms.ToArray(), p[p.Length - 1]); // 

        }
    }

When running the aboce code I get the following error -

Client found response content type of 'text/html', but expected 'text/xml'.

Any idea what is causing this error ?

By the looks of things after some research, it looks like it is a form of a error page coming back. Go have a look here as well as here .

Hope this gives you some form of clarification on your problem.

Hey buddy if the main purpose of your method is just to upload a file you can use :

FileUpload fu;  // Get the FileUpload object.
using (FileStream fs = File.OpenWrite("file.dat"))
{
    fu.PostedFile.InputStream.CopyTo(fs);
    fs.Flush();
}

That will be more efficient, as you will be directly streaming the input file to the destination host, without first caching in memory or on disk.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM