duanlinpi0265 2018-05-22 10:56
浏览 64

如何在图片上传中更改XmlHttpRequest网址

I am trying to upload image and it is working. but the problem is when I am trying to update this image I m having problem because it is redirecting to wrong url. The form is post to this url

POST http://127.0.0.1/mgt/upload/processImage/foodImage

and the result is coming like this

GET
http://127.0.0.1/mgt/food/viewFoodDetails/temp/uploads/images/foodImage/937d932fcbf3c6ba36b7eed65cecd045.png

But, I want the get result should come like this (I dont want it to get food/viewFoodDetails from url)

GET http://127.0.0.1/mgt/temp/uploads/images/foodImage/937d932fcbf3c6ba36b7eed65cecd045.png

can anyone help me please?

here is my js

$.fn.uploadFile=function(opts)
    {
        var opts=$.extend({
            allowed:['png, jpg']
        },opts);
        return this.each(function(){
            var pb='<div class="progress" style="width:0"><span>0%</span></div>',
            _this=$(this),
            progressbar=$(_this.attr("data-progressbar")),
            endpoint='http://127.0.0.1/mgt/upload/processImage/foodImage',
            viewer=$(_this.attr("data-viewer")),
            element=$(_this.attr("data-element")),
            downloadLink=$(_this.attr("data-downloadLink"));
            //cct=$(_this).parents("form").find("input[name=csrfwebpos]").val();
            //console.log(_this, progressbar, endpoint, viewer, element, downloadLink);
            _this.change(function(){
                var filename=_this.val().toLowerCase().split(/[\\\/]/).pop(),is_allowed=false,
                ext=filename.split(".").pop();
                //console.log(filename, ext);
                if(filename==''){
                    return;
                }
                $.each(opts.allowed,function(i,el){
                    if(ext==el){
                        is_allowed=true;
                    }
                });
                if(!is_allowed){
                    showError("This file type is not supported. Please select another file.");
                    return;
                }else{
                    progressbar.show(0);
                    var files=_this[0].files,
                    file=_this[0].files[0], 
                    headers={
                            "Cache-Control":"no-cache",
                            "X-Requested-With":"XMLHttpRequest",
                            "X-File-Name":file.fileName||file.name,
                            "X-File-Size":file.fileSize||file.size,

                    };
                    if(file.size>700000){
                        showError("File can not be larger than 700KB in size.");
                        return;
                    }
                    _this.attr("disabled",true);
                    progressbar.append(pb);
                    var bar=progressbar.find(".progress"),percent=bar.find("span");

                    var xhr = new XMLHttpRequest();
                    var upload = xhr.upload;
                    upload.fileObj = file;
                    upload.downloadStartTime = new Date().getTime();
                    upload.currentStart = upload.downloadStartTime;
                    upload.currentProgress = 0;
                    upload.startData = 0;
                    viewer.hide(0);

                    upload.onprogress=function(e){
                        if(e.lengthComputable){
                            var _p=Math.floor((e.loaded/e.total)*100);
                            bar.css("width",_p+"%");
                            percent.html(_p+"%");
                            if(_p==100){
                                percent.html("Processing...");
                            }
                        }
                    };

                    xhr.onload=function(e){
                        status = xhr.status;
                        if(e.target.readyState == 4){
                            var data=eval("("+this.responseText+")");

                            console.log(this);
                            console.log(data);

                            if(data && data.successFunction){
                                data.successFunction.apply(_this);
                            }
                            if(data && data.fileName!=''){
                                element.val(data.fileName);
                                element.trigger("change");
                                viewer.show(0);
                                $(viewer).find("img").prop("src",data.fileName);
                            }
                            if(data && data.downloadLink!=''){
                                downloadLink.html('<a href="'+data.downloadLink+'">Download Server Response</a>');
                            }

                            _this.val("").attr("disabled",false);
                            progressbar.find(".progress").remove();
                            progressbar.hide(0);
                        }
                    };
                    xhr.open("POST",endpoint,true);

                    //console.log(endpoint);

                    /*
                    var oMyForm = new FormData();
                    oMyForm.append("csrfwebpos", cct);
                    oMyForm.append("file", file);
                    */
                    for(var prop in headers){

                        xhr.setRequestHeader(prop, headers[prop]);
                    }
                    xhr.send(file);
                }
            });
        });
    };

This is my image upload function upload.php

public function processImage($uploadFolder="profile", $userFileName="")
    {
        $tempFilePath="temp/$uploadFolder";

        if (!file_exists($tempFilePath)) {
            @mkdir($tempFilePath);
        }
        @chmod($tempFilePath, 0777);
        $path=$tempFilePath."/";

        $headers=getallheaders();

        if (isset($headers['X-File-Size'], $headers['X-File-Name'])) {
            // create the object and assign property
            $file = new stdClass;
            $file->name = basename($headers['X-File-Name']);
            $file->size = $headers['X-File-Size'];
            $file->content = file_get_contents("php://input");

            $fileparts=fileExtension($file->name);
            if ($userFileName=='') {
                $filename = md5(
                    $this->session->userdata('userid') . 
                    uniqid() . 
                    microtime(true) . 
                    mt_rand() . 
                    $file->name . 
                    $file->size . 
                    $this->session->userdata('userid')
                );
            } else {
                $filename=$userFileName;
            }
            $file->name=$filename.$fileparts["extension"];
           // echo $path.$file->name;

            if (@file_put_contents($path.$file->name, $file->content)) {
                $old = getcwd(); // Save the current directory
                @chdir($path);
                chmod($file->name, 0644);
                chdir($old);


            }
        } 
    }

This is my HTML

<script type='text/javascript'>
    $(document).ready(function() {
        $('#uploadImage').uploadFile();
    });
</script>

        <form method='post' action='<?=$baseUrl?>food/saveFood' accept-charset='utf-8'  enctype='multipart/form-data'>

        <table class='table table-bordered table-curved'>
            <tr>
                <td>
                    <div class='form-group col-md-12' style='padding:0px;'>
                        <div class='fileupload fileupload-new' data-provides='fileupload'>
                            <div class='input-group'>
                                <div class='form-control uneditable-input'><i class='icon-file fileupload-exists'></i> 
                                    <span class='fileupload-preview'></span>
                                </div>
                                <div class='input-group-btn'>
                                    <a class='btn btn-default btn-file'>
                                        <span class='fileupload-new'>Select file</span>
                                        <span class='fileupload-exists'>Change</span>
                                        <input type='file' class='file-input' id='uploadImage' data-progressbar='.pb' data-element='#appImg' data-viewer='#appPhoto' />
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class='clearfix'></div>
                    <div class='pb pull-left col-md-12' style='display:none;'></div>
                    <div id='appPhoto'><img src='' /></div>
                    <input type='hidden' name='imagePath' id='appImg' value='' />

                </td>
    </form>
  • 写回答

1条回答 默认 最新

  • duancai7568 2018-05-24 08:21
    关注

    I solved it, I have added baseurl to the file path

    from
    $(viewer).find("img").prop("src",data.fileName);

    to $(viewer).find("img").prop("src",baseurl+data.fileName);

    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值