通过预览上传图片

时间:2014-07-24 11:41:00

标签: javascript jquery html css

我正在为论坛用户创建上传功能,因此他们可以上传个人照片。到目前为止我得到了什么:

HTML

<label>Profile image</label>
<div class="photo" id="photoPreview"></div>
<input type="file" value="forumPhoto" onchange="return changePhoto(this);">

JAVASCRIPT

function showPhotoPreview() {
    var photoUrl = $.trim($("#photo").val());
    var img = $("#photoPreview img");
    if (photoUrl != "") {
        if (img.length == 0) {
            img = $("<img />").appendTo($("#photoPreview"));
        }
        img.prop("src", photoUrl);
    }
    else {
        img.remove();
    }
}

function changePhoto(sender) {
    var value = $(sender).val();
    sender.selectedIndex = 0;
    switch (value) {
        case "upload":
            assignPicture();
            break;
    }
    showPhotoPreview();
    return false;
}

function assignPicture() {
    var forumPhoto = $("#forumPhoto").val();
    if (forumPhoto == "") {
        alert("You must specify an address to use forumPhoto.");
        return;
    }
    $("#photo").val(forumPhoto);
}

目前的问题是它没有出现在预览图片中。 JsFiddle:http://jsfiddle.net/qLsY7/

2 个答案:

答案 0 :(得分:1)

您需要HTML5(FileReader)或Flash才能完成您要执行的操作。 简单地说,Javascript / iFrames可以防止处理本地用户文件并在浏览器中查看它们以防止恶意使用。

对于使用Mootools 1.3.2的工作示例,您可以将其转换为jQuery。我必须覆盖XHR方法才能处理请求,所以你很可能需要对jQuery做同样的事情。请注意,我检查了FileReader并删除了没有它的预览功能。

您还可以调整window.FormData方法以激活上传过程,并使用服务器源更新onSuccess上的图像。

http://examples.torntech.com/ajax_file/

HTML:

       <div id="wrapper">
            <form id="ajaxFileForm" method="post" action="processFile.php" enctype="multipart/form-data">
                <input id="imageToUpload" name="file" type="file"><br>
                <input name="somefield" type="text" value="Hello World"><br>
                <button id="previewBtn" type="button" disabled="">Preview</button>
                <button id="uploadBtn" type="submit" disabled="">Upload</button>
            </form>
            <div id="previewWrapper">
                <h4>Preview Image:</h4>
                <img style="display:none;" src="/assets/img/pixel.gif" id="preview" alt="Image Preview">
                <div id="info"></div>
            </div>
            <hr style="height:1px; border:0; background: #666;">
            <div id="responseWrapper" style="display: none">
                <h4>Response:</h4>
                <div id="output"></div>
            </div>
        </div>

使用Javascript:

//<![CDATA[
        Request.implement({
            options: {
                form: null
            },
            sendFile: function(options){
                if (!this.check(options)) return this;

                this.options.isSuccess = this.options.isSuccess || this.isSuccess;
                this.running = true;

                var type = typeOf(options);
                if (type == 'string' || type == 'element') options = {data: options};

                var old = this.options;
                options = Object.append({data: old.data, url: old.url, method: old.method, form: old.form, sendAsBinary: old.sendAsBinary}, options);
                var data = options.data, url = String(options.url);

                if (!url) url = document.location.pathname;

                var trimPosition = url.lastIndexOf('/');
                if (trimPosition > -1 && (trimPosition = url.indexOf('#')) > -1) url = url.substr(0, trimPosition);

                if (this.options.noCache)
                    url += (url.contains('?') ? '&' : '?') + String.uniqueID();

                var xhr = this.xhr;
                xhr.open("POST", url, this.options.async, this.options.user, this.options.password);
                if (this.options.user && 'withCredentials' in xhr) xhr.withCredentials = true;

                xhr.onreadystatechange = this.onStateChange.bind(this);

                Object.each(this.headers, function(value, key){
                    try {
                        xhr.setRequestHeader(key, value);
                    } catch (e){
                        this.fireEvent('exception', [key, value]);
                    }
                }, this);

                this.fireEvent('request');
                if(options.form){
                    data = new FormData();
                    options.form.getChildren('input').each(function(el){
                        var name = el.get('name'),
                        value = (el.get('type') == 'file')? el.files[0] : el.get('value');
                        data.append(name, value);
                    });
                }
                xhr.send(data);
                if (!this.options.async) this.onStateChange();
                if (this.options.timeout) this.timer = this.timeout.delay(this.options.timeout, this);
                return this;
            }
        });

        addEvent('domready', function(){
            var preview = $('preview'),
            output = $('output'),
            info = $('info'),
            previewWrapper = $('previewWrapper'),
            responseWrapper = $('responseWrapper'),
            previewBtn = $('previewBtn'),
            imageToUpload = $('imageToUpload'),
            wrapper = $('wrapper'),
            uploadBtn = $('uploadBtn'),
            bothBtns = new Elements([uploadBtn, previewBtn]),
            isFileReader = true,
            fileTypes = {
                'jpeg' : true,
                'png' : true,
                'bmp' : true,
                'jpg': true
            },
            fileToUpload = null,
            maxSize =   2986000,
            initReader = function(){
                if(!isFileReader)
                    return false;
                var reader = new FileReader();
                //Chrome doesn't initiatize this - so onload only occurs when the object is created.
                reader.onload = function () {
                    preview.set('src', reader.result);
                    preview.setStyle('display', 'inline');
                };
                return reader;
            },
            testFile = function(fileToUpload){
                if(!(fileTypes[fileToUpload.type.replace('image/', '')])){
                    alert('Please select a valid image.');
                    return false;
                }
                if(fileToUpload.size > maxSize){
                    alert('Filesize limit of ' + maxSize + ' exceeded.');
                    return false;
                }
                return true;
            },
            getPreview = function(e){
                bothBtns.set('disabled', 'disabled');
                preview.set('src', '/assets/img/pixel.gif');

                fileToUpload = $('imageToUpload').files[0];
                if(!fileToUpload)
                    return true;

                info.set('html', '<ul><li><strong>'+ fileToUpload.name + '</strong> (' + (fileToUpload.type || 'N/A') + ') ' + fileToUpload.size + ' bytes</li></ul>');
                if(testFile(fileToUpload)){
                    bothBtns.removeProperty('disabled');
                    var reader = initReader();
                    if(!reader)
                        return true;
                    reader.readAsDataURL(fileToUpload);
                    if(e && e.type != 'submit'){
                        var scroll = previewWrapper.getPosition().y;
                        scrollFx.start(0, scroll);
                    }
                    return true;
                }
                return false;
            },
            scrollFx = new Fx.Scroll(window, {wheelStops: false}),
            myRequest = new Request({
                url: 'processFile.php',
                headers: {
                    'Sender' : 'XMLHttpRequest'
                },
                onRequest: function(){
                    output.set('html', "<p>Loading...</p>");
                    var scroll = responseWrapper.getPosition().y;
                    scrollFx.start(0, scroll);
                },
                onSuccess: function(text){
                    var scroll = responseWrapper.getPosition().y;
                    scrollFx.start(0, scroll);
                    output.set('html', text);
                }
            });

            if(typeof(window.FormData) === 'undefined'){
                $$('#ajaxFileForm, hr, #responseWrapper').dispose();
                wrapper.set('html', '<p>Your browser does not support FormData - For XHR File Uploads</p>');
                return;
            }
            if(typeof(window.FileReader) === 'undefined'){
                isFileReader = false;
                previewBtn.dispose();
                previewWrapper.set('html', '<p>Your browser does not support File API - For Previews</p>');
            }
            $('ajaxFileForm').addEvent('submit', function(e){
                e.stop();
                if(!getPreview(e))
                    return false;
                responseWrapper.setStyle('display', 'block');
                var formData = $('ajaxFileForm');
                myRequest.sendFile({form: formData});
            });
            imageToUpload.addEvent('change', getPreview);
            previewBtn.addEvent('click', getPreview);
            getPreview();
        });
        //]]>

答案 1 :(得分:0)

请试试。

HTML:

<form runat="server">
    <input type="file" id="imgInput">
    <img src="#" alt="image" id="img">
</form>

的JavaScript:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function(e) {
            $('#img').attr('src', e.target.result;)
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$('#imgInput').change(function() {
    readURL(this);
});