mapic
mapic
  • 发布:2015-06-12 13:16
  • 更新:2015-06-14 16:00
  • 阅读:5063

不使用input而通过FormData上传文件,服务器总是报500错误,贴出代码,求助高手

分类:MUI
mui
2015-06-12 13:16 负责人:无 分享
已邀请:
mapic

mapic (作者)

通过上面注释掉的代码,即使用ajax上传,服务器完全没响应。不使用input标签上传文件困扰我好多天了,跪求高手解答如何解决500错误,或者如何通过ajax上传文件

做做

做做

我是用的jquery的插件自己修改,并加入https://github.com/think2011/localResizeIMG3进行图片客户端压缩上传只是这种方式需要在服务器端另外做一个接口处理post过来的图片base64编码

下面是我的上传插件,用到了jquery 你也可以修改成mui的

/*  
 * Uploader.js - Jquery File Uploader - 0.1  
 * http://www.daniel.com.uy/projects/jquery-file-uploader/  
 *  
 * Copyright (c) 2013 Daniel Morales  
 * Dual licensed under the MIT and GPL licenses.  
 * http://www.daniel.com.uy/doc/license/  
 */  

(function($) {  
    var pluginName = 'uploader';  

    // These are the plugin defaults values  
    var defaults = {  
        url: document.URL,  
        method: 'POST',  
        formData: {},  
        maxFileSize: 0,  
        allowedTypes: '*',  
        extFilter: null,  
        dataType: null,  
        fileName: 'file',  
        compress: false,  
        onInit: function() {},  
        onFallbackMode: function(message) {},  
        onChangeFile: function() {},  
        onNewFile: function(id, file) {},  
        onBeforeUpload: function(id) {},  
        onComplete: function() {},  
        onUploadProgress: function(id, percent) {},  
        onUploadSuccess: function(id, data) {},  
        onUploadError: function(id, message) {},  
        onFileTypeError: function(file) {},  
        onFileSizeError: function(file) {},  
        onFileExtError: function(file) {}  
    };  

    var Uploader = function(element, options) {  
        this.element = $(element);  

        this.settings = $.extend({}, defaults, options);  

        if (!this.checkBrowser()) {  
            return false;  
        }  

        this.init();  

        return true;  
    };  

    /**  
     * 是否支持本地压缩  
     */  
    Uploader.prototype.compressSupport = function(){  
        return typeof window.URL !== 'undefined' || typeof document.createElement('canvas').getContext !== 'function';  
    }  

    Uploader.prototype.checkBrowser = function() {  
        if (window.FormData === undefined) {  
            this.settings.onFallbackMode.call(this.element, '浏览器不支持 Form API');  
            return false;  
        }  

        if (this.element.attr('type') == 'file' || this.element.find('input[type=file]').length > 0) {  
            return true;  
        }  
        return true;  
    };  

    Uploader.prototype.checkEvent = function(eventName, element) {  
        var element = element || document.createElement('div');  
        var eventName = 'on' + eventName;  

        var isSupported = eventName in element;  

        if (!isSupported) {  
            if (!element.setAttribute) {  
                element = document.createElement('div');  
            }  
            if (element.setAttribute && element.removeAttribute) {  
                element.setAttribute(eventName, '');  
                isSupported = typeof element[eventName] == 'function';  

                if (typeof element[eventName] != 'undefined') {  
                    element[eventName] = undefined;  
                }  
                element.removeAttribute(eventName);  
            }  
        }  

        element = null;  
        return isSupported;  
    };  

    Uploader.prototype.init = function() {  
        var self = this;  

        self.queue = [];  
        self.queuePos = -1;  
        self.queueRunning = false;  

        var obj;  
        if (this.element.attr('type') == 'file') {  
            obj = this.element;  
        } else if(this.element.find('input[type=file]').length > 0) {  
            obj = this.element.find('input[type=file]');  
        }  

        obj.on('change', function(evt) {  
            evt = evt || window.event;  
            self.settings.onChangeFile.call(this.element);  
            var files = evt.target.files;  
            if (!files.length) {  
                return false  
            }  

            self.queueFiles(files);  

            $(this).val('');  
        });  

        this.settings.onInit.call(this.element);  
    };  

    Uploader.prototype.queueFiles = function(files) {  
        var j = this.queue.length;  

        for (var i = 0; i < files.length; i++) {  
            var file = files[i];  

            // Check file size  
            if ((this.settings.maxFileSize > 0) && (file.size > (this.settings.maxFileSize * 1024))) {  
                this.settings.onFileSizeError.call(this.element, file);  
                continue;  
            }  

            // Check file type  
            if ((this.settings.allowedTypes != '*') && !file.type.match(this.settings.allowedTypes)) {  
                this.settings.onFileTypeError.call(this.element, file);  
                continue;  
            }  

            // Check file extension  
            if (this.settings.extFilter != null) {  
                var extList = this.settings.extFilter.toLowerCase().split(';');  

                var ext = file.name.toLowerCase().split('.').pop();  

                if ($.inArray(ext, extList) < 0) {  
                    this.settings.onFileExtError.call(this.element, file);  
                    continue;  
                }  
            }  

            this.queue.push(file);  

            var index = this.queue.length - 1;  

            this.settings.onNewFile.call(this.element, index, file);  
        }  

        // Only start Queue if we haven't!  
        if (this.queueRunning) {  
            return false;  
        }  

        // and only if new Files were succefully added  
        if (this.queue.length == j) {  
            return false;  
        }  

        this.processQueue();  

        return true;  
    };  

    Uploader.prototype.processQueue = function() {  
        var self = this;  

        self.queuePos++;  

        if (self.queuePos >= self.queue.length) {  
            // Cleanup  
            self.settings.onComplete.call(self.element);  

            // Wait until new files are droped  
            self.queuePos = (self.queue.length - 1);  

            self.queueRunning = false;  

            return;  
        }  

        var file = self.queue[self.queuePos];  

        // Form Data  
        var data = new FormData();  

        // Append add Form Data  
        $.each(self.settings.formData, function(exKey, exVal) {  
            if(typeof exVal == 'object') { //如果是object则用jquery的val方法取得内容  
                exVal = exVal.val();  
            }  
            data.append(exKey, exVal);  
        });  

        // 客户端压缩上传  
        if(self.settings.compress && self.compressSupport && file.type != 'image/gif') {  
            Q.use('mobileFix', 'exif', 'lrz', function() {  
                lrz(file, {  
                    done: function (results) {  
                        file = results.base64.replace(/data:.+;base64,/, '');  
                        data.append('updateType', 'base64');  
                        data.append('fileName', results.origin.name);  
                        data.append('base64Len', results.base64Len);  
                        data.append(self.settings.fileName, file);  
                        self.settings.onBeforeUpload.call(self.element, self.queuePos);  
                        self.queueRunning = true;  
                        self.post(data);  
                        results.base64 = null;  
                    }  
                });  
            });  
            return;  
        } else {  
            data.append(self.settings.fileName, file);  
            self.settings.onBeforeUpload.call(self.element, self.queuePos);  
            self.queueRunning = true;  
            self.post(data);  
        }  
    };  

    Uploader.prototype.post = function(data) {  
        var self = this;  

        $.ajax({  
            url: this.settings.url,  
            type: this.settings.method,  
            dataType: this.settings.dataType,  
            data: data,  
            cache: false,  
            contentType: false,  
            processData: false,  
            forceSync: false,  
            beforeSend:function(jqXHR, settings) {  
                settings.url = Q.util.getUrl(settings.url);  
                jqXHR.setRequestHeader('X-CSRF-Token', cfg.token);  
                jqXHR.setRequestHeader('X-Requested-With','XMLHttpRequest');  
            },  
            xhr: function() {  
                var xhrobj = $.ajaxSettings.xhr();  
                if (xhrobj.upload) {  
                    xhrobj.upload.addEventListener('progress', function(event) {  
                        var percent = 0;  
                        var position = event.loaded || event.position;  
                        var total = event.total || e.totalSize;  
                        if (event.lengthComputable) {  
                            percent = Math.ceil(position / total * 100);  
                        }  
                        self.settings.onUploadProgress.call(self.element, self.queuePos, percent);  
                    }, false);  
                }  
                return xhrobj;  
            },  
            success: function(data, message, xhr) {  
                if(data.errno === '0') {  
                    self.settings.onUploadSuccess.call(self.element, self.queuePos, data.data);  
                } else {  
                    self.settings.onUploadError.call(self.element, self.queuePos, data.message);  
                }  
            },  
            error: function(xhr, status, errMsg) {  
                self.settings.onUploadError.call(self.element, self.queuePos, errMsg);  
            },  
            complete: function(xhr, textStatus) {  
                self.processQueue();  
            }  
        });  
    };  

    Uploader.prototype.parseSize = function(size) {  
        var i = Math.floor( Math.log(size) / Math.log(1024) );  
        return ( size / Math.pow(1024, i) ).toFixed(2) * 1 + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i];  
    };  

    $.fn.uploader = function(options) {  
        return this.each(function() {  
            if (!$.data(this, pluginName)) {  
                $.data(this, pluginName, new Uploader(this, options));  
            }  
        });  
    };  

})(jQuery);

服务器接收到图片base64数据后解密
$file = base64_decode($file);
然后使用 file_put_contents 函数存储为图片
file_put_contents($filename, $file);

希望对你有用

该问题目前已经被锁定, 无法添加新回复