weixin_33699914 2019-01-17 10:42 采纳率: 0%
浏览 60

正在上传base64 pdf

I am making a file manager. Now I ran into the problem while trying to upload pdf files. The code I have so far that uploads images is working fine. When i convert the pdf to a base64 string and open it in an tab, it shows the correct file and is working.

When I upload the file it uploads correctly, however when i open the uploaded file it seems to be corrupted.

Piece of code for uploading files i have:

JavaScript:

if(files[0].type.match(/\/pdf$/)){
 var reader = new FileReader();
 reader.readAsDataURL(files[0]);
 reader.onload = function () {
  uploadFile(reader.result, 'pdf', 'pdf', files[0].name);
  console.log(reader.result); //shows correct base64
 };
 reader.onerror = function (error) {
  console.log('Error: ', error);
 };
}


function uploadFile(file, name, type, file_name) {
  var file_name = file_name.split('.')[0];
  var $row = renderFileUploadRow(file_name, name);
  $('body').append($row);
  var fd = new FormData();
  fd.append('file_data', file);
  fd.append('do', 'upload');
  fd.append('type', type);
  fd.append('name', name)
  fd.append('file_name', file_name);
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'control.php?');
  xhr.onload = function(data) {
    $row.remove();
  };
  xhr.upload.onprogress = function(e) {
    if (e.lengthComputable) {
      $row.find('.progress').css('width', (e.loaded / e.total * 100 | 0) + '%');
    }
  };
  xhr.send(fd);
}

PHP receiving the ajax call:

if ($_POST['do'] == 'upload') {
  $type = $_POST['type'];
    $img = $_POST['file_data'];
    $img = str_replace('data:image/'.$type.';base64,', '', $img);
  echo "$type";
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
  if ($type == 'jpeg') {
    $type = 'jpg';
  }
  define('UPLOAD_DIR', 'data/'.$_POST['name'].'/');
    $upload = UPLOAD_DIR . $_POST['file_name'] . '.'.$type;
  if (file_exists($upload)==1){
    $nummer = '1';
    while(file_exists(UPLOAD_DIR . $_POST['file_name'] .'('. $nummer . ').'.$type)) {
      $nummer++;
    }
    $upload = UPLOAD_DIR . $_POST['file_name'] .'('. $nummer .').'.$type;
  }
    $success = file_put_contents($upload, $data);
  exit;
}

I expected to upload correctly because when i made images first and tested it, the files were uploaded correct. Now it uploads but the file is corrupted.

What am i doing wrong here?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 求差集那个函数有问题,有无佬可以解决
    • ¥15 【提问】基于Invest的水源涵养
    • ¥20 微信网友居然可以通过vx号找到我绑的手机号
    • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
    • ¥15 解riccati方程组
    • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
    • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
    • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
    • ¥50 树莓派安卓APK系统签名
    • ¥65 汇编语言除法溢出问题