简体   繁体   中英

jquery, how to upload image of input(file) via webservice to codebehind and read there

i want to save a input (type = file) image to database (asp.net & mssql),
in this case i use web service, so i can't use runat= server, or i can't use server side controls.

in client side, user chose a picture, and i must save it binary to database.

var exts = ['jpg', 'jpeg', 'png', 'gif'];  
var file = $(this).val();
if (file) {
                var get_ext = file.split('.');
                get_ext = get_ext.reverse();
                if ($.inArray(get_ext[0].toLowerCase(), exts) > -1) {
                    if ((Math.round((this.files[0].size) / 1024)) > 35) {
                        alert("PLEASE REDUCE FILE SIZE");
                    } else {
                        //everything is ok
                    }
                } else {
                    alert("PLEASE CORRECT FORMAT");
                }
            } else {
                alert("PLEASE DEFINE FILE");
  }

i can check file selected, type and size and know need to upload.

what can i do? is it possible to support, ie? if yes which version?

thank you

You have to upload the image in a form using the next tag:

<form id='fileUploadForm' enctype="multipart/form-data" method="post" action="yourAction">          
<input type="hidden" value="your max value in bytes" name="MAX_FILE_SIZE">
<input type="file" name="userImage">
</form>

It will be submitted for any browser.

But if you want to submit the form using ajax, you should use a plugin. I used recently this one: http://malsup.github.io/jquery.form.js . It is very simply to use.

There is another issue: files[0] will return undefined if using IE.

I use this so that IE also works:

var file = $('input[type=file]')
file.bind('change', function(e) {
    e.preventDefault();
    if (typeof this.files === "undefined") fileOk = file;
    else fileOk = this.files[0];
            ....

Then, and after validation on client side, you can use this method from jquery.form plugin:

$('#fileUploadForm').ajaxSubmit(){
    beforeSend: function() {},
    uploadProgress: function(event, position, total, percentComplete) {},
    success: function() {},
    complete: function(xhr) {}
}

And the file will be submitted.

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