16

Well, the files attribute of an input[type=file] is read-only. Therefore I can not write my blob data into this input element.

But if I create a new input file element using Javscript, then possible to insert blob data on creation? I am only interested in solutions working in chrome (extension) - other browsers do not matter.

2
  • 3
    I've recently tried it, and it's not possible. The only use case for wanting to modify the file in <input type=file> is when you want to change a file prior uploading. If you're looking for a method to accomplish that, use the FormData function from the XMLHttpRequest level 2 specification. Code examples can be found at stackoverflow.com/a/11628694 (possibly duplicate question?) and stackoverflow.com/a/11382138
    – Rob W
    Commented Jul 31, 2012 at 12:31
  • @RobW Setting the value of a file input it also a convenient way to indicate to the user that their upload is valid/invalid, especially when they have the option to choose a file from disk or create the file in-browser (i.e. via getUserMedia). That's my use case - filling out a file input box from a microphone when the browser doesn't support that by default (which few browsers do).
    – Brilliand
    Commented Mar 12, 2015 at 21:32

2 Answers 2

2

new File() constructor is available at chromium / chrome 38+. See File Constructor Sample , File API.

var date = new Date(),
  filename = "file-" + date.getTime() + ".html";

var generatedFile = new File(
  ["<!DOCTYPE html><html><body>" + filename + "</body></html>"]
  , filename
  , {
  type: "text/html",
  lastModified: date
  }
);

var objUrl = URL.createObjectURL(generatedFile);

console.log(generatedFile, objUrl);

var reader = new FileReader();

reader.addEventListener("load", function(event) {
  console.log(event.target.result)
});

reader.readAsText(generatedFile);

0

You can check my example for process file to input, url to input as blob, input to img tag preview https://vulieumang.github.io/vuhocjs/file2input-input2file/

var btnLoadUrl = document.querySelector('#loadUrl');
btnLoadUrl.addEventListener("click", ()=>{
  var url = document.querySelector('#url').value;
  loadURLToInputField(url)
});

var btnLoadImage = document.querySelector('#loadImage');
btnLoadImage.addEventListener("click", ()=>{
  var img_preview = document.querySelector('#img-preview');
  console.log(img_preview)
  loadInputFieldToPreview(img_preview)
});

var file_browser = document.querySelector('#file_browser');
var img_preview2 = document.querySelector('#img-preview2');
file_browser.addEventListener('change',()=>{
  var reader = new FileReader();
  reader.onload = function(e) {
    img_preview2.src = e.target.result
  }
  reader.readAsDataURL(document.querySelector('#file_browser').files[0]);
})

function loadURLToInputField(url){
  getImgURL(url, (imgBlob)=>{
    // Load img blob to input
    // WIP: UTF character error
    let fileName = 'hasFilename.jpg'
    let file = new File([imgBlob], fileName,{type:"image/jpeg", lastModified:new Date().getTime()}, 'utf-8');
    let container = new DataTransfer(); 
    container.items.add(file);
    document.querySelector('#file_input').files = container.files;
    // document.querySelector('#status').files = container.files;
    
  })
}

function loadInputFieldToPreview(imgElement){
  // Load preview to img tag
  var reader = new FileReader();
  reader.onload = function(e) {
    imgElement.src = e.target.result
  }
  reader.readAsDataURL(document.querySelector('#file_input').files[0]); // convert to base64 string
}

// xml json res
function httpGetAsync(url, callback){
  var req = new XMLHttpRequest();
  req.responseType = 'json';
  req.open('GET', url);
  req.onload  = function() {
    var jsonResponse = req.response;
    callback(jsonResponse)
    // do something with jsonResponse
  };
  req.send(null);
}

// xml blob res
function getImgURL(url, callback){
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
      callback(xhr.response);
  };
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();
}

//check input status
setInterval(() => {
  var input = document.querySelector('#file_input');
  var status = document.querySelector('#status');
  if(input.value){
    status.innerHTML = 'has input'
    
  } else {
    status.innerHTML = 'empty input'
  }
}, 500);
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>URL, file to input and preview</title>
  
</head>
<body>
  <h1>Load URL to input</h1>
  <input width="100%" id='url' type="text" placeholder="paste url image here" value="https://cloudinary-res.cloudinary.com/image/upload/dpr_2.0,c_scale,f_auto,q_auto,w_156/cloudinary_logo_for_white_bg.svg">
  <button id="loadUrl">Load URL to input type file</button>
  <input id='file_input' type="file">
  <span>status input file type: <span id="status"></span></span>
 
  <h1>Load input to preview</h1>
  <button id="loadImage" >Load input above to preview</button>
  <img src="" id='img-preview' alt="img-preview">

  <h1>Load input file browser to preview</h1>
  <input type="file" name="" id="file_browser">
  <img src="" id='img-preview2' alt="preview2">

  <script src="script.js"></script>
</body>
</html>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.