weixin_33725239 2019-03-05 11:41 采纳率: 0%
浏览 33

Javascript AJAX上传文件

I have written a script in JavaScript to handle a file drag and drop. When the 'drop' listen is called the file is captured using dataTransfer.files (function below).

    event.preventDefault(); 
    event.stopPropagation();
    console.log(event.dataTransfer.files[0]);
    uploadFiles = event.dataTransfer.files; 
    fileBoxUpLoad(uploadFiles);

Console log shows the file appears to be capture correctly

File {name: "Changi - 2016.pdf", lastModified: 1473382409845, lastModifiedDate: Fri Sep 09 2016 10:53:29 GMT+1000 (Australian Eastern Standard Time), webkitRelativePath: "", size: 197754, …}

The fileBoxUpLoad function is call and when the code gets to the xmlhttp.send it throws an error

Unexpected token o in JSON at position 1 at JSON.parse ()

var formData = new FormData();
    for(var x=0; x<=item.length; x++) 
    {
        formData.append('file', item[x]);
    }

    var xmlhttps = new XMLHttpRequest();
    xmlhttps.open("POST", uri);
    xmlhttps.setRequestHeader('Content-Type', file.type);
    xmlhttps.send(formData);

I understand this means I am trying to parse an Javascript object, when I don't think I am and I can't see where my code is any different to all the tutorials I have read. Any advice? Thanks!!

  • 写回答

1条回答 默认 最新

  • weixin_33694620 2019-03-05 12:56
    关注

    You can do something like this

    //declare an array for store the files
    var uploadedFiles = [];
    
    //then get files by using their id or maybe you can loop through on your control
    var file = $('input[name=YourControlName]').get(0).files[0];
    
    //push the files to array
    uploadedFiles.push(file);
    
    //declare form data and append files to form data
    var formData = new FormData();   
    for (var i = 0; i < uploadedFiles.length; i++) {
        formData.append("file" + i, uploadedFiles[i]);
    }
    
    //then you can post to via ajax and get on api via request files
    $.ajax({
    type: "post",
    url: "",
    contentType: false,
    data: formData,
    processData: false,
    success: function (result) {
        alert(result);
    },
    failure: function (e) {
        alert(e);
    }
    

    });

    评论

报告相同问题?

悬赏问题

  • ¥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系统的硬盘