user1226051
user1226051

Reputation: 13

can i upload a user-selected image to server using web service?

I am doing a ASP .NET website where among other things a user can upload an image, that needs to be saved to the server.

In the whole website I'm trying to accomplish as minimal communication between the client and server as possible. This means that on onload() I invoke web services which return all data needed for that page, and then manipulate them using javascript.

So far, it has worked flawlessly. The problem arises when a user wishes to make changes to his profile. I can take all the information entered in the text fields and the sort, and pass them as arguments to a webservice which saves them to the database. The thing I dont know how to do, or if it is even possible, is to pass the selected image as an argument to the webservice.

I am using html5: <input type="file"> for the image selection

Upvotes: 1

Views: 1455

Answers (2)

DJ Quimby
DJ Quimby

Reputation: 3699

If you use the asp:FileUpload control instead, when the user clicks submit you can do something similar to the following in the page's code-behind:

protected void UploadButton_Click( object sender, EventArgs e ) {
    if ( !ImageUpload.HasFile ) {
        return;
    }

    string imageBase64 = System.Convert.ToBase64String( ImageUpload.FileBytes );

    YourService service = new YourService();

    service.UploadImage( imageBase64 );

This assumes of course that your service has a method called UploadImage that takes a string as a parameter.

Then on the back end, convert the string to a byte array:

byte[] imageArray = System.Convert.FromBase64String( base64ImageData );

And save it as binary data to your database.

As a warning, you may want to add length checks on the webpage to prevent someone from uploading images that are too large... otherwise your server could be bogged down.

Upvotes: 1

helle
helle

Reputation: 11650

You should use a html formular. But you need to change some of the default configuration of the form-tag

<form action="url" method="post" enctype="multipart/form-data">
    <input type="file" name="my-file" />
</form>

and you can use an iframe as target of the form, than the page does not reload. You can react on the iframe then...

<form ... target="youriframe">

see this website for a full example

Upvotes: 0

Related Questions