JS gets the physical path of the input tag type = "file" to solve the problem of browser C: \ fakepath \

After clicking to upload the picture, the onchange event gets the way to upload the picture

Very helpless, I got a fake path like C: \ fakepath \ aa.jpg

Baidu checked out:

This is due to the security mechanism of the browser, and the path of the input file is replaced by fakepath, which hides the real physical path. 

Solution:

 

1. Adjust the browser security settings of the browser (not recommended or reasonable).

2. Use window.URL.createObjectURL ()

				var url = null;  
				var fileObj = document.getElementById("uplaodImg").files[0];
				if (window.createObjcectURL != undefined) {  
				    url = window.createOjcectURL(fileObj);  
				} else if (window.URL != undefined) {  
				    url = window.URL.createObjectURL(fileObj);  
				} else if (window.webkitURL != undefined) {  
				    url = window.webkitURL.createObjectURL(fileObj); 
				}
				// console.log(url)
				if(url){
					$('#user_avatar').attr('src',url)

				}

  

Explanation:

The URL.createObjectURL () method creates a URL pointing to the parameter object based on the parameters passed in. The life of the URL only exists in the document it was created,
The new object URL points to the executed File object or Blob object. 
语法:objcetURL = window.URL.createObjectURL(file || blob); 
Parameters: File object and Blob object; File object is a file, for example, I use the file type = "file" tag to upload a file, then each file in it is
A file object. The Blob object is binary data. For example, in XMLHttpRequest, if the requestType is specified as blob, then the returned value is also
A blob object. 
Each time createObjectURL is called, a new URL object is created. Even if you have created a URL for the same file, if you no longer need this
Object, to release it, you need to use the URL.revokeObjectURL () method. When the page is closed, the browser will automatically release it, but for best performance and memory usage,
When it is ensured that it is no longer needed, it should be released.

  

 

Guess you like

Origin www.cnblogs.com/Mishell/p/12746407.html