简体   繁体   中英

Get all images in folder

I have a function to get product information from the getProduct database and an ImageInfo function that gets the product image depending on the product ID assigned to it.

The name of each image is ID @ 0, ID @ 1 .... The ID is the same as the product ID.

To get the image, I get the product ID and through it run a query where I get the image whose name is ID @ 0.

How can I fetch all images from the folder? That is, now I do not just want the ID @ 0, now I want to get all and if possible with different requests (without receiving them all in the same request, for performance reasons).

Can anyone help me?

Component.ts

  GetProducts() {
    let self = this;
    this.Global.refreshToken()
      .subscribe(function (result) {
        self.fileService.getProducts(self.paramProductId)
          .then(function (resultado) {
            if (resultado) {
              self.products = resultado; 
            }
          })
          .then(() => {
            if (self.products) {
              return Promise.all(self.products.map((product) => self.ImageInfo(product.id)));
            }
          })
          .catch((err) => console.error(err));
      });
  }

  ImageInfo(id) {
    var self = this;
    this.Global.refreshToken().subscribe(function (result) {
      self.fileService.getImages(id).then(function (resultado) {
        if (resultado) {
          self.imagMap.set(id,resultado);
        }
      }).catch();

    });
  }

service.ts

 getProducts(id): Promise<any> {
        let self = this;
        let urlAux = self.url + "/Products/GetProducts?id=" + id;
        return axios.get(urlAux, {
          headers: {
            Authorization: 'Bearer ' + localStorage.getItem("access_token")
          }
        })
          .then(this.extraData)
          .catch(this.handleErroPromisse);
      }

      getImages(id): Promise<any> {
        let self = this;
        let urlAux = self.url + "/Products/GetImagesFile/" + id;

        return axios.get(urlAux, {'responseType': 'arraybuffer'})
          .then((response) => {
            let image = btoa(
              new Uint8Array(response.data)
                .reduce((data, byte) => data + String.fromCharCode(byte), '')
            );
            return `data:${response.headers['content-type'].toLowerCase()};base64,${image}`;
          });
      }

Service C#

public MemoryStream GetImagesFile(SqlConnection conn, int id, out string contentType, Dictionary<string, string> confRede)
        {
            contentType = "";
            try
            {

                SqlCommand cmd = conn.CreateCommand();
                conn.Open();
                cmd.CommandText = @"SELECT CAT.[Path] + '\' + CAST(PRD.ID AS VARCHAR) + '\' + CAST(PRD.ID AS VARCHAR) + '@0.' + 'jpg' AS [Caminho] 
                    FROM [dbo].[Products] AS [PRD] 
                    INNER JOIN[dbo].[Categories] AS[CAT] on PRD.IDCategory = CAT.ID WHERE PRD.Id = @ID";

                cmd.Parameters.Add("@ID", SqlDbType.Int).Value = id;

                string caminho = cmd.ExecuteScalar().ToString();

                NetworkConnection acesso = new Global.Global().AccessToServer(confRede);
                using (acesso)
                {
                    new FileExtensionContentTypeProvider().TryGetContentType(caminho, out contentType);

                    var memory = new MemoryStream();
                    using (var stream = new FileStream(caminho, FileMode.Open))
                    {

                        stream.CopyTo(memory);
                    }
                    memory.Position = 0;
                    return memory;
                }
            }
            catch (Exception ex)
            {

                return null;
            }
            finally
            {
                conn.Close();
            }
        }

If you have the path to the directory, in C# you can use the GetFiles(string path) method in System.IO to retrieve the contents of the directory.

You'll end up with a string array containing the filenames of each file in the directory.

Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM