Read image from URL & upload

后端 未结 3 1858
眼角桃花
眼角桃花 2021-01-21 02:09

I am not able to find a proper way to read an image from a URL and upload it using JavaScript/Ajax.

Suppose there is a URL: https://pbs.twimg.com/profile_images/15

相关标签:
3条回答
  • 2021-01-21 02:50

    If the remote server allows CORS requests, it possible to download a remote image and read its contents. If the remote server does not allow CORS, the image can be shown (using a standard <img src=".."> tag), but the content cannot be read - the canvas gets tainted.

    Download image from remote URL using JavaScript when CORS is enabled

    function getImageFormUrl(url, callback) {
      var img = new Image();
      img.setAttribute('crossOrigin', 'anonymous');
      img.onload = function (a) {
    	var canvas = document.createElement("canvas");
    	canvas.width = this.width;
    	canvas.height = this.height;
    	var ctx = canvas.getContext("2d");
    	ctx.drawImage(this, 0, 0);
    
    	var dataURI = canvas.toDataURL("image/jpg");
    	  
    	// convert base64/URLEncoded data component to raw binary data held in a string
    	var byteString;
    	if (dataURI.split(',')[0].indexOf('base64') >= 0)
    		byteString = atob(dataURI.split(',')[1]);
    	else
    		byteString = unescape(dataURI.split(',')[1]);
    
    	// separate out the mime component
    	var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
    
    	// write the bytes of the string to a typed array
    	var ia = new Uint8Array(byteString.length);
    	for (var i = 0; i < byteString.length; i++) {
    		ia[i] = byteString.charCodeAt(i);
    	}
    
    	return callback(new Blob([ia], { type: mimeString }));
      }
      
      img.src = url;
    }
    
    
    getImageFormUrl('https://upload.wikimedia.org/wikipedia/commons/thumb/b/b4/The_Sun_by_the_Atmospheric_Imaging_Assembly_of_NASA%27s_Solar_Dynamics_Observatory_-_20100819.jpg/628px-The_Sun_by_the_Atmospheric_Imaging_Assembly_of_NASA%27s_Solar_Dynamics_Observatory_-_20100819.jpg', function (blobImage) {
    	var formData = new FormData();
    	formData.append('key1', 'value1');
    	formData.append('key2', 'value2');
    	formData.append('key2', 'value3');
    	formData.append('imageToUpload', blobImage);
    	
    	console.log(blobImage);
    	//use formData in "data" property in $.ajax
    	//$.ajax({
    		//blabla: blabla,
    		//data: formData,
    		//blabla: blabla
    	//}})
    });

    0 讨论(0)
  • 2021-01-21 02:52

    @DheerajAgrawal

    see this example: http://jsfiddle.net/WQXXT/3004/

    you should customize that, where it says:

    alert('start upload script here');
    
    0 讨论(0)
  • 2021-01-21 02:57

    Let server download/upload your image. What you need to do is to create a text input field for image URL. Than via AJAX you send to backend the URL only and server gets its contents.

    0 讨论(0)
提交回复
热议问题