Hướng dẫn convert image path to blob javascript - chuyển đổi đường dẫn hình ảnh sang blob javascript

Tham khảo: Filereader.ReadAsDataurl

Xem xét ví dụ sau:

function previewFile(file) {

  var reader  = new FileReader();

  reader.onloadend = function () {
    console.log(reader.result);
  }
  reader.readAsDataURL(file);
}

Nó nói:

instanceOfFileReader.readAsDataURL(blob);

BLOB: Blob hoặc tập tin để đọc.

  1. Làm thế nào một url tệp cục bộ có thể như:

    var request = new XMLHttpRequest();
    request.open('GET', MY_URL, true);
    request.responseType = 'blob';
    request.onload = function() {
        var reader = new FileReader();
        reader.readAsDataURL(request.response);
        reader.onload =  function(e){
            console.log('DataURL:', e.target.result);
        };
    };
    request.send();
    
    0 được chuyển đến
    var request = new XMLHttpRequest();
    request.open('GET', MY_URL, true);
    request.responseType = 'blob';
    request.onload = function() {
        var reader = new FileReader();
        reader.readAsDataURL(request.response);
        reader.onload =  function(e){
            console.log('DataURL:', e.target.result);
        };
    };
    request.send();
    
    1

  2. var request = new XMLHttpRequest();
    request.open('GET', MY_URL, true);
    request.responseType = 'blob';
    request.onload = function() {
        var reader = new FileReader();
        reader.readAsDataURL(request.response);
        reader.onload =  function(e){
            console.log('DataURL:', e.target.result);
        };
    };
    request.send();
    
    2 có sẵn trong một addon firefox không?

Hỏi ngày 30 tháng 7 năm 2014 lúc 20:27Jul 30, 2014 at 20:27

Hướng dẫn convert image path to blob javascript - chuyển đổi đường dẫn hình ảnh sang blob javascript

Erosmanerosmanerosman

6.4067 Huy hiệu vàng24 Huy hiệu bạc45 Huy hiệu Đồng7 gold badges24 silver badges45 bronze badges

Để chuyển đổi URL thành Blob cho Filereader.ReadAsDataurl () làm điều này:

var request = new XMLHttpRequest();
request.open('GET', MY_URL, true);
request.responseType = 'blob';
request.onload = function() {
    var reader = new FileReader();
    reader.readAsDataURL(request.response);
    reader.onload =  function(e){
        console.log('DataURL:', e.target.result);
    };
};
request.send();

Đã trả lời ngày 19 tháng 1 năm 2017 lúc 21:37Jan 19, 2017 at 21:37

Felix Turnerfelix TurnerFelix Turner

1.2301 huy hiệu vàng9 Huy hiệu bạc1 gold badge9 silver badges7 bronze badges

3

Mở rộng trên phản hồi của Felix Turner, đây là cách tôi sử dụng phương pháp này với API

var request = new XMLHttpRequest();
request.open('GET', MY_URL, true);
request.responseType = 'blob';
request.onload = function() {
    var reader = new FileReader();
    reader.readAsDataURL(request.response);
    reader.onload =  function(e){
        console.log('DataURL:', e.target.result);
    };
};
request.send();
3.

async function createFile(){
  let response = await fetch('http://127.0.0.1:8080/test.jpg');
  let data = await response.blob();
  let metadata = {
    type: 'image/jpeg'
  };
  let file = new File([data], "test.jpg", metadata);
  // ... do something with the file or return it
}
createFile();

Đã trả lời ngày 2 tháng 12 năm 2018 lúc 19:51Dec 2, 2018 at 19:51

Hướng dẫn convert image path to blob javascript - chuyển đổi đường dẫn hình ảnh sang blob javascript

Tibor Udvaritibor UdvariTibor Udvari

2.8223 huy hiệu vàng22 Huy hiệu bạc39 Huy hiệu đồng3 gold badges22 silver badges39 bronze badges

5

Hàng đợi chỉnh sửa được đề xuất là đầy đủ cho câu trả lời xuất sắc tuyệt vời của @Tibor-Udvari, vì vậy tôi sẽ đăng các chỉnh sửa được đề xuất của mình như một câu trả lời mới.@tibor-udvari's excellent fetch answer, so I'll post my suggested edits as a new answer.

Chức năng này nhận được loại nội dung từ tiêu đề nếu được trả về, nếu không, sẽ trở lại với một loại mặc định có thể giải quyết được.

async function getFileFromUrl(url, name, defaultType = 'image/jpeg'){
  const response = await fetch(url);
  const data = await response.blob();
  return new File([data], name, {
    type: data.type || defaultType,
  });
}

// `await` can only be used in an async body, but showing it here for simplicity.
const file = await getFileFromUrl('https://example.com/image.jpg', 'example.jpg');

Bất tận

31.3k11 Huy hiệu vàng104 Huy hiệu bạc127 Huy hiệu đồng11 gold badges104 silver badges127 bronze badges

Đã trả lời ngày 23 tháng 9 năm 2020 lúc 10:06Sep 23, 2020 at 10:06

Hướng dẫn convert image path to blob javascript - chuyển đổi đường dẫn hình ảnh sang blob javascript

KristakristaKrista

5666 Huy hiệu bạc5 Huy hiệu Đồng6 silver badges5 bronze badges

Hãy thử điều này, tôi đã học được điều này từ @nmaier khi tôi đang chuyển đổi thành ICO: Tôi không thực sự hiểu bộ đệm mảng là gì nhưng nó làm những gì chúng ta cần:

function previewFile(file) {

  var reader  = new FileReader();

  reader.onloadend = function () {
    console.log(reader.result); //this is an ArrayBuffer
  }
  reader.readAsArrayBuffer(file);
}

Lưu ý cách tôi vừa thay đổi

var request = new XMLHttpRequest();
request.open('GET', MY_URL, true);
request.responseType = 'blob';
request.onload = function() {
    var reader = new FileReader();
    reader.readAsDataURL(request.response);
    reader.onload =  function(e){
        console.log('DataURL:', e.target.result);
    };
};
request.send();
4 của bạn thành
var request = new XMLHttpRequest();
request.open('GET', MY_URL, true);
request.responseType = 'blob';
request.onload = function() {
    var reader = new FileReader();
    reader.readAsDataURL(request.response);
    reader.onload =  function(e){
        console.log('DataURL:', e.target.result);
    };
};
request.send();
5.

Đây là ví dụ @Nmaier đã cho tôi: https://stackoverflow.com/a/24253997/1828637

nó có một fiddle

Nếu bạn muốn lấy cái này và tạo một tệp ra khỏi nó, tôi nghĩ rằng bạn sẽ sử dụng luồng đầu ra tệp trong

var request = new XMLHttpRequest();
request.open('GET', MY_URL, true);
request.responseType = 'blob';
request.onload = function() {
    var reader = new FileReader();
    reader.readAsDataURL(request.response);
    reader.onload =  function(e){
        console.log('DataURL:', e.target.result);
    };
};
request.send();
6

Đã trả lời ngày 30 tháng 7 năm 2014 lúc 20:38Jul 30, 2014 at 20:38

NoitidartnoitidartNoitidart

33,8K33 Huy hiệu vàng133 Huy hiệu bạc301 Huy hiệu Đồng33 gold badges133 silver badges301 bronze badges

6

Thông tin này đã lỗi thời như bây giờ, nhưng không thể bị xóa.

  1. Bạn có thể tạo các phiên bản

    var request = new XMLHttpRequest();
    request.open('GET', MY_URL, true);
    request.responseType = 'blob';
    request.onload = function() {
        var reader = new FileReader();
        reader.readAsDataURL(request.response);
        reader.onload =  function(e){
            console.log('DataURL:', e.target.result);
        };
    };
    request.send();
    
    7 chỉ bằng cách chỉ định một đường dẫn khi mã của bạn được đặc quyền chrome:

    new File("/path/to/file");
    

    var request = new XMLHttpRequest();
    request.open('GET', MY_URL, true);
    request.responseType = 'blob';
    request.onload = function() {
        var reader = new FileReader();
        reader.readAsDataURL(request.response);
        reader.onload =  function(e){
            console.log('DataURL:', e.target.result);
        };
    };
    request.send();
    
    7 là một lớp phụ của
    var request = new XMLHttpRequest();
    request.open('GET', MY_URL, true);
    request.responseType = 'blob';
    request.onload = function() {
        var reader = new FileReader();
        reader.readAsDataURL(request.response);
        reader.onload =  function(e){
            console.log('DataURL:', e.target.result);
        };
    };
    request.send();
    
    9, vì vậy tất cả các trường hợp
    var request = new XMLHttpRequest();
    request.open('GET', MY_URL, true);
    request.responseType = 'blob';
    request.onload = function() {
        var reader = new FileReader();
        reader.readAsDataURL(request.response);
        reader.onload =  function(e){
            console.log('DataURL:', e.target.result);
        };
    };
    request.send();
    
    7 cũng có giá trị
    var request = new XMLHttpRequest();
    request.open('GET', MY_URL, true);
    request.responseType = 'blob';
    request.onload = function() {
        var reader = new FileReader();
        reader.readAsDataURL(request.response);
        reader.onload =  function(e){
            console.log('DataURL:', e.target.result);
        };
    };
    request.send();
    
    9s. Xin lưu ý rằng điều này yêu cầu một đường dẫn nền tảng và không phải là URL tệp.

  2. Có,

    async function createFile(){
      let response = await fetch('http://127.0.0.1:8080/test.jpg');
      let data = await response.blob();
      let metadata = {
        type: 'image/jpeg'
      };
      let file = new File([data], "test.jpg", metadata);
      // ... do something with the file or return it
    }
    createFile();
    
    2 có sẵn cho addons.

var request = new XMLHttpRequest();
request.open('GET', MY_URL, true);
request.responseType = 'blob';
request.onload = function() {
    var reader = new FileReader();
    reader.readAsDataURL(request.response);
    reader.onload =  function(e){
        console.log('DataURL:', e.target.result);
    };
};
request.send();
7 và
async function createFile(){
  let response = await fetch('http://127.0.0.1:8080/test.jpg');
  let data = await response.blob();
  let metadata = {
    type: 'image/jpeg'
  };
  let file = new File([data], "test.jpg", metadata);
  // ... do something with the file or return it
}
createFile();
2 có sẵn trong tất cả các
async function createFile(){
  let response = await fetch('http://127.0.0.1:8080/test.jpg');
  let data = await response.blob();
  let metadata = {
    type: 'image/jpeg'
  };
  let file = new File([data], "test.jpg", metadata);
  // ... do something with the file or return it
}
createFile();
5s. Nếu bạn muốn sử dụng chúng trong phạm vi không cửa sổ (như
async function createFile(){
  let response = await fetch('http://127.0.0.1:8080/test.jpg');
  let data = await response.blob();
  let metadata = {
    type: 'image/jpeg'
  };
  let file = new File([data], "test.jpg", metadata);
  // ... do something with the file or return it
}
createFile();
6 hoặc mô-đun mã), bạn có thể sử dụng ____ 27/________ 28.

Đã trả lời ngày 30 tháng 7 năm 2014 lúc 20:42Jul 30, 2014 at 20:42

Nmaiernmaiernmaier

31.6K5 Huy hiệu vàng61 Huy hiệu bạc77 Huy hiệu đồng5 gold badges61 silver badges77 bronze badges

8

Đây là mã của tôi bằng cách sử dụng Async đang chờ đợi và hứa hẹn

const getBlobFromUrl = (myImageUrl) => {
    return new Promise((resolve, reject) => {
        let request = new XMLHttpRequest();
        request.open('GET', myImageUrl, true);
        request.responseType = 'blob';
        request.onload = () => {
            resolve(request.response);
        };
        request.onerror = reject;
        request.send();
    })
}

const getDataFromBlob = (myBlob) => {
    return new Promise((resolve, reject) => {
        let reader = new FileReader();
        reader.onload = () => {
            resolve(reader.result);
        };
        reader.onerror = reject;
        reader.readAsDataURL(myBlob);
    })
}

const convertUrlToImageData = async (myImageUrl) => {
    try {
        let myBlob = await getBlobFromUrl(myImageUrl);
        console.log(myBlob)
        let myImageData = await getDataFromBlob(myBlob);
        console.log(myImageData)
        return myImageData;
    } catch (err) {
        console.log(err);
        return null;
    }
}

export default convertUrlToImageData;

Đã trả lời ngày 6 tháng 5 năm 2020 lúc 17:31May 6, 2020 at 17:31

Hướng dẫn convert image path to blob javascript - chuyển đổi đường dẫn hình ảnh sang blob javascript

JbaiLeyjbaileyjbailey

2994 Huy hiệu bạc6 Huy hiệu Đồng4 silver badges6 bronze badges

1

Tôi biết đây là một bản mở rộng của câu trả lời của @Tibor-Udvari, nhưng đối với một bản sao và dán đẹp hơn.

async function createFile(url, type){
  if (typeof window === 'undefined') return // make sure we are in the browser
  const response = await fetch(url)
  const data = await response.blob()
  const metadata = {
    type: type || 'video/quicktime'
  }
  return new File([data], url, metadata)
}

Đã trả lời ngày 11 tháng 9 năm 2020 lúc 16:33Sep 11, 2020 at 16:33

Alex Coryalex CoryAlex Cory

9.4047 Huy hiệu vàng49 Huy hiệu bạc62 Huy hiệu Đồng7 gold badges49 silver badges62 bronze badges

Cuối cùng tôi đã muốn một cái gì đó tương tự như thế này nhưng không phải truyền loại cho tệp hoặc tên tệp, vì vậy tôi đã tự làm ví dụ của mình dựa trên ví dụ của @Felix Turner. Tôi đã sử dụng tiêu đề

async function createFile(){
  let response = await fetch('http://127.0.0.1:8080/test.jpg');
  let data = await response.blob();
  let metadata = {
    type: 'image/jpeg'
  };
  let file = new File([data], "test.jpg", metadata);
  // ... do something with the file or return it
}
createFile();
9 cho tên tệp trước tiên trong trường hợp tệp sẽ quay lại từ điểm cuối API, nhưng sử dụng phần cuối của đường dẫn URL nếu tiêu đề đó không tồn tại.

function getFilenameFromContentDisposition(res) {
  let filename = null;

  const disposition = res.headers.get("content-disposition");

  if (disposition?.includes("attachment")) {
    const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
    const matches = filenameRegex.exec(disposition);
    if (matches?.[1]) {
      filename = matches[1].replace(/['"]/g, "");
      // Sometimes the filename comes in a URI encoded format so decode it
      filename = decodeURIComponent(filename);
      // Sometimes the filename starts with UTF-8, remove that
      filename = filename.replace(/^UTF-8/i, "").trim();
    }
  }

  return filename;
}

async function getFileFromLink(url) {
  const fileRes = await fetch(url);
  const blob = await fileRes.blob();

  let fileName = getFilenameFromContentDisposition(fileRes);
  if (!fileName) {
    fileName = url.split("/").pop();
  }

  const file = new File([blob], fileName, {
    type: blob.type,
  });

  return file;
}

Nếu bạn muốn làm cho việc này tốt hơn, tôi sẽ sử dụng gói

async function createFile(){
  let response = await fetch('http://127.0.0.1:8080/test.jpg');
  let data = await response.blob();
  let metadata = {
    type: 'image/jpeg'
  };
  let file = new File([data], "test.jpg", metadata);
  // ... do something with the file or return it
}
createFile();
9 trên NPM để phân tích cú pháp làm định dạng của nó có thể trở nên lạ. Tôi cũng có thể sử dụng gói
async function getFileFromUrl(url, name, defaultType = 'image/jpeg'){
  const response = await fetch(url);
  const data = await response.blob();
  return new File([data], name, {
    type: data.type || defaultType,
  });
}

// `await` can only be used in an async body, but showing it here for simplicity.
const file = await getFileFromUrl('https://example.com/image.jpg', 'example.jpg');
1 để đảm bảo tên tệp từ URL có phần mở rộng tệp phù hợp dựa trên
async function getFileFromUrl(url, name, defaultType = 'image/jpeg'){
  const response = await fetch(url);
  const data = await response.blob();
  return new File([data], name, {
    type: data.type || defaultType,
  });
}

// `await` can only be used in an async body, but showing it here for simplicity.
const file = await getFileFromUrl('https://example.com/image.jpg', 'example.jpg');
2 đã trả lại

Đã trả lời ngày 2 tháng 6 lúc 21:59Jun 2 at 21:59

Hướng dẫn convert image path to blob javascript - chuyển đổi đường dẫn hình ảnh sang blob javascript

Đây là một cách đơn giản nhất để có được blob hoặc đối tượng tập tin với vanila.js và hứa hẹn

const fileURL_to_blob = (file_url) => {
  return new Promise((resolve, reject) => {
    let request = new XMLHttpRequest();
    request.open('GET', file_url, true);
    request.responseType = 'blob';
    request.onload = function() {
        var reader = new FileReader();
        reader.readAsDataURL(request.response);
        reader.onload =  function(e){
            //console.log('DataURL:', e.target.result);
            resolve(e.target.result);
        };
    };
    request.onerror=function(e){
      reject(e);
    }
    request.send();
  });
}

Đã trả lời ngày 5 tháng 1 lúc 8:09Jan 5 at 8:09

Hướng dẫn convert image path to blob javascript - chuyển đổi đường dẫn hình ảnh sang blob javascript

Readasdataurl là gì?

Phương pháp Readasdataurl được sử dụng để đọc nội dung của blob hoặc tệp được chỉ định. Khi hoạt động đọc kết thúc, ReadyState sẽ hoàn thành và tải được kích hoạt. Vào thời điểm đó, thuộc tính kết quả chứa dữ liệu dưới dạng dữ liệu: URL đại diện cho dữ liệu của tệp dưới dạng chuỗi được mã hóa base64.used to read the contents of the specified Blob or File . When the read operation is finished, the readyState becomes DONE , and the loadend is triggered. At that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string.

Làm thế nào tôi có thể nhận được kết quả của Filereader?

Nó hoạt động bằng cách tạo một đối tượng Filereader và tạo trình nghe cho các sự kiện tải sao cho khi đó tệp được đọc, kết quả được lấy và chuyển đến chức năng gọi lại được cung cấp để đọc ().Nội dung được xử lý dưới dạng dữ liệu văn bản thô.creating a FileReader object and creating a listener for load events such that when then file is read, the result is obtained and passed to the callback function provided to read() . The content is handled as raw text data.

Blob trong JavaScript là gì?

Một đối tượng Blob chỉ đơn giản là một nhóm các byte chứa dữ liệu được lưu trữ trong một tệp.Có vẻ như một Blob là một tham chiếu đến tệp thực tế nhưng thực sự nó không phải là.Một blob có kích thước và mime của nó giống như một tệp đơn giản.

Liên kết Blob là gì?

Blob URL/Object URL là giao thức giả để cho phép các đối tượng blob và tệp được sử dụng làm nguồn URL cho những thứ như hình ảnh, tải xuống liên kết cho dữ liệu nhị phân, v.v.Ví dụ: bạn không thể trao một đối tượng hình ảnh Byte Byte vì nó sẽ không biết phải làm gì với nó.