weixin_33749131 2015-05-02 07:07 采纳率: 0%
浏览 15

用ajax上传图片

I know, there are many tutorials, but I can't figure out how to make them work.

I have an input form for file upload:

<input onChange="userPreviewImage(this)" type="file" accept="image/*" style="display:none"/>

There is my Javascript code

function userPreviewImage (fileInput) {
    save = true;
    var files = fileInput.files;
    var file = files[0];
    current = file;
    var imageType = /image.*/;
    var img = document.createElement("img");

    img.classList.add("obj");
    img.classList.add("preview");
    img.file = file;

    var reader = new FileReader();
    reader.onload = (function(aImg) { 
        return function(e) { 
            aImg.src = e.target.result; 
        }; 
    })(img);
    reader.readAsDataURL(file);
}

As a result I have img, which is an object <img src="data:image/png;base64..."> which I can print out.

I've been using this for a while, but now I need to change the workflow. My goal now is instead of printing the image, send its source to the server (the server code is working fine). I can't figure out how to get the image source from what I have (just the data:image/png;base64... part). Can someone give me a tip?

  • 写回答

1条回答 默认 最新

  • weixin_33725126 2015-05-02 09:06
    关注

    Try posting data URI aImg to server as String

    window.onload = function () {
        this.userPreviewImage = function (fileInput) {
            var files = fileInput.files;
            var file = files[0];
            var reader = new FileReader();
            reader.onload = function (aImg) {
                $.post("/echo/html/", {
                    html: aImg.target.result
                })
                .then(function (data, textStatus, jqxhr) {
                    console.log(data, textStatus);
                }, function(jqxhr, textStatus, errorThrown) {
                    console.log(textStatus, errorThrown);
                })
            };
            reader.readAsDataURL(file);
        }
    };
    

    jsfiddle http://jsfiddle.net/8gjb82b6/1/

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘