How to create a blob of a JS script in front-end

In the app I am developing, I need at some point to export a ZIP File containing and index.html and a script.js. The index.html is created depending on the app state, and I have no problem with it. The script.js however is more a problem to me: I don’t know how to include it in the ZIP file. Let me show you the whole process:

In createZipFile.js :

 import JSZip from 'jszip'; import script from './script';  const createHtml = (data) => `<html lang="en"><head><meta charset="UTF-8"></head><body>$  {data}</body><script type="text/javascript">$  {script}</script></html>`  const createZIPFile = async (data) => {   const zip = new JSZip();   zip.file("index.html", createHtml(data));   return await zip.generateAsync({ type: 'blob' }); }  

In script.js :

const script = `   const doSomething = () => {     console.log('I do something')   } `;  export default script;  

Of course, the script I want to inject is much more complex, and also it has a dependency. But it does not change depending on the state of the app.

What I do today is: create a side project, with the script and its dependencies, make a production build out of it (minified), and copy paste all this new code as a string in the script variable. It’s not perfect for maintenance…

Is there a way to do differently, only from the front-end ? For example, is there a way to create a blob out of a real script, and do something like that :

In createZipFile.js :

 import JSZip from 'jszip'; import script from './script';  const createHtml = (data) => `<html lang="en"><head><meta charset="UTF-8"></head><body>$  {data}</body><script type="text/javascript" src="/script.js"></script></html>`  const createZIPFile = async (data) => {   const zip = new JSZip();   zip.file("index.html", createHtml(data));   zip.file("script.js", script);   return await zip.generateAsync({ type: 'blob' }); }  

In script.js

const doSomething = () => {   console.log('I do something') } 

How to create a blob of a JS script in front-end

In the app I am developing, I need at some point to export a ZIP File containing and index.html and a script.js. The index.html is created depending on the app state, and I have no problem with it. The script.js however is more a problem to me: I don’t know how to include it in the ZIP file. Let me show you the whole process:

In createZipFile.js :

 import JSZip from 'jszip'; import script from './script';  const createHtml = (data) => `<html lang="en"><head><meta charset="UTF-8"></head><body>$  {data}</body><script type="text/javascript">$  {script}</script></html>`  const createZIPFile = async (data) => {   const zip = new JSZip();   zip.file("index.html", createHtml(data));   return await zip.generateAsync({ type: 'blob' }); }  

In script.js :

const script = `   const doSomething = () => {     console.log('I do something')   } `;  export default script;  

Of course, the script I want to inject is much more complex, and also it has a dependency. But it does not change depending on the state of the app.

What I do today is: create a side project, with the script and its dependencies, make a production build out of it (minified), and copy paste all this new code as a string in the script variable. It’s not perfect for maintenance…

Is there a way to do differently, only from the front-end ? For example, is there a way to create a blob out of a real script, and do something like that :

In createZipFile.js :

 import JSZip from 'jszip'; import script from './script';  const createHtml = (data) => `<html lang="en"><head><meta charset="UTF-8"></head><body>$  {data}</body><script type="text/javascript" src="/script.js"></script></html>`  const createZIPFile = async (data) => {   const zip = new JSZip();   zip.file("index.html", createHtml(data));   zip.file("script.js", script);   return await zip.generateAsync({ type: 'blob' }); }  

In script.js

const doSomething = () => {   console.log('I do something') } 

How change large dataset between access tiers in Azure Blob Storage

I have an ML dataset that consists of 2.7M images, ~1TB. For ML experiments, I uploaded these as blobs in an Azure storage account under “hot” access (which I thought would be appropriate for ML training). While not actively training, I would like this dataset to be in “Archive” mode to avoid accumulating “leaky faucet” charges.

The document on blob storage access tiers describes how it can be toggled on a per-blob basis, but AFAICT that is per-file (not even per-directory, which would be fine).

Is there a way to toggle the access tier of an entire storage account?

Absent that, what might be a good strategy? Perhaps creating a default-archive-access data_archive storage account and do a cloud-based copy to a temporary data_for_training_purposes hot-access storage account that I create and delete as needed?

Flushing the BLOB cache best practice

So i need to flush the BLOB cache on our SharePoint 2013 site. Found the below code on multiple sites but wondering if it should be done out of hours or just during the day.

My limited understanding is that all the files get reset back to 1KB and as people load pages in SharePoint the files are re-stored in the BLOB cache location we have specified. So pages might be initially a little slower to load but then back to normal?

$  webApp = Get-SPWebApplication "<WebApplicationURL>" [Microsoft.SharePoint.Publishing.PublishingCache]::FlushBlobCache($  webApp) Write-Host "Flushed the BLOB cache for:" $  webApp 

I also came across the fact i should also have the below in there as well, which leads me to believe our side of core hours.

iireset 

Can anyone advise?

what is the best appraoch to store files for our asp.net core web application (Blob, FileStream or File system)

I am build a new asp.net core MVC web application, the web application is a workflow based system which will be accessed by different users, as follow:-

  1. the workflow will have 10++ steps.

  2. Inside each step there will be a tab to upload and store files (images, pds, office, etc..).

  3. The system will prevent duplicate files names to be uploaded inside the same step, but will allow this to be done on separate tabs.

  4. Users can add a description for each of the uploaded file + define if the file can be viewed by all users or only by selected users (define a privacy setting for each file).

Now i am not sure which appraoch i should follow to store the files:-

  1. Blob

  2. FileStream

  3. or store them on the windows drive (file system)

now i read many articles about this, and generally people suggest to store the files outside the database, as database is designed to store structured data, and also to prevent increasing the database size. so maybe i can exclude using the Blob ,, but bot sure what will be the pros and cons of using FileStream compared to storing the files directly to the File system?

Note, now we are planning to host the web application to a cloud provider (Azure for example), so we will chose to use the latest version of sql server. also we are thinking of using Entity framework core as our data access tool, so can this force us to exclude using FileStream as EF-core does not support FileStream directly?

Fetch Blob Imagen con React Native Expo

tengo una imagen en un enpoint como este.

https://d1na8u9bbyf6pn.cloudfront.net/twt-uat1/MUS2014123113584242167/69093975526/105000000204082.jpeg?Expires=1539883894&Signature=ONFNJ1XTY3FOLUIMDnrcpR7~Awuobkwx~P5Ab~4hYx5bnVf5fSKwAzbobWZNnYrmzVXHGiyUmVEfRSvuZtseaMJfx6y1Bs9oI5ewuLRf-r0zMn25gFsN228FQ3IBaki3BsXJXQ-d~yVfhlkA6rIxQ1bHxnJ0VOgxEr6UU9g8gny2NIHwQTppJwFQYyAOtY1yBQ7KtlWp-WcasQVcCZn0H7tG59a7rpBCFUcfaFozQS0Dduizyl972vuHBY6V6o2KiCTWRrTNnXvFMLTfzVYb8UXl9USbwHP2nGvnqAfYhYIlm4KeYcJU4VZC66iWypcOPrpfJkdokHmgXltkbJJHbA__&Key-Pair-Id=APKAJER34WYXWHOJ2NZQ 

Pero cuando el fetch al enpoint y luego el .blob me dice que la imagen pesa 0kb, hay alguna manera de conseguir la imagen de un endpoint para poder utilizarla en React Native Expo ?

Un saludo.

Mostrar imágenes tipo blob de mysql con Spring

¿Cómo puedo imprimir una lista de imagenes almacenada en una base de datos con Spring MVC?

He tratado hacer de la siguiente manera pero las imágenes no se muestran

BrandController.java

package controller;  import dao.Connect; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import model.Brand; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import services.BrandService;  @Controller public class BrandController {      Connect con = new Connect();     JdbcTemplate jdbcTemplate = new JdbcTemplate(con.Connect());     ModelAndView mav = new ModelAndView();       private BrandService brandService;      @RequestMapping("brands.htm")     public ModelAndView List() {         String sql = "select * from brands";         List data = this.jdbcTemplate.queryForList(sql);         mav.addObject("brandsList", data);          mav.setViewName("brands");         return mav;     }           @RequestMapping(value = "/images/brands", method = RequestMethod.GET)     public void showImage(@RequestParam("id") int brand_id, HttpServletResponse response, HttpServletRequest request)            throws ServletException, IOException{          Brand brand = brandService.getBrand(brand_id);                 response.setContentType("image/jpeg, image/jpg, image/png");         response.getOutputStream().write(brand.getBrand_logo());         response.getOutputStream().close();         } } 

BrandDao.java

package dao;  import model.Brand;  public interface BrandDao {      Brand selectBrand(int brand_id); } 

BrandService.java

package services;  import dao.BrandDao; import model.Brand; import org.springframework.stereotype.Service;  @Service public class BrandService {     private final BrandDao brandDao;      public BrandService(BrandDao brandDao) {         this.brandDao = brandDao;     }      public Brand getBrand(int brand_id) {         return brandDao.selectBrand(brand_id);     } } 

brand.jsp

... <div class="row">     <c:forEach items="$  {brandsList}" var="brand">          <div>              <a href="#">                  <span><img src="/images/brands?$  {brand.brand_id}"/></span>                  <span><c:out value="$  {brand.brand_name}"/></span>              </a>          </div>     </c:forEach> </div> ... 

Por favor si me podrían ayudar? Muchas gracias de antemano.

gerar PDF com imagem BLOB da JLabel que vem do banco de dados mysql no itext

Bom dia, Estou com um programa java desktop e o meu problema está em gerar PDF com o itext, com a imagem BLOB vinda do banco de dados mysql, a mesma está sendo mostrada na JLabel dentro de um JPanel com um select.

package classes_conexao;  import java.awt.Color; import java.awt.EventQueue; import java.awt.Font; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.util.logging.Logger;  import javax.swing.BorderFactory; import javax.swing.DefaultComboBoxModel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import javax.swing.text.MaskFormatter;  import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Image; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.BaseColor;  import classes_conexao.pdf.exemplo3_tableComDadosdoBanco; import javax.swing.JTextPane; import java.awt.FlowLayout;  public class Certificados extends JFrame {      private static final int BOLD = 0;     private JPanel contentPane;     private JTextField txt_prPresidente;     private JTextField txt_prDirigente;     private JTextField txt_titCertificado;     private JTextField txt_Certificado;     private JTextField txt_data;     private JComboBox cb_TpCertificado;     private JButton btn_imprimir;     private JTextPane txt_Mensagem;     private JComboBox cb_assinatura;      private JPanel pn_assinatura;     private JLabel lbl_rubrica;     private JPanel pn_dirigente;     private JLabel lbl_Dirigente;     private JComboBox cb_prDirigente;      /**      * Launch the application.      */     public static void main(String[] args) {         EventQueue.invokeLater(new Runnable() {             public void run() {                 try {                     Certificados frame = new Certificados();                     frame.setVisible(true);                 } catch (Exception e) {                     e.printStackTrace();                 }             }         });     }      public void geraPdf(String tipodecertificado, String data, String imagedir, String pastorpresidente, String assinatura, String assinaturadir, String pastordirigente, String titulocertificados, String mensagem) throws SQLException {         Document documento = new Document(PageSize.A4.rotate());          try {              OutputStream outputStream = new FileOutputStream("Certificado.pdf");                 PdfWriter.getInstance(documento,outputStream);                 documento.open();//abre o arquivo                 //adicionando texto para o pdf                  // conexão com o banco de dados                  ....cóigo....                    ImageIcon img = (ImageIcon)lbl_Dirigente.getIcon();                 documento.add(img);                  ...Código...                  documento.close();                 JOptionPane.showMessageDialog(null, "Certificado gerado com sucesso");                  Process p = Runtime.getRuntime().exec("cmd.exe /C Certificado.pdf");                        } catch (FileNotFoundException e1) {             JOptionPane.showMessageDialog(null, e1);             e1.printStackTrace();         }          catch (MalformedURLException e11) {             // TODO Auto-generated catch block             e11.printStackTrace();         }          catch (IOException e) {             // TODO Auto-generated catch block             e.printStackTrace();         }         catch (DocumentException e111) {             Logger.getLogger(exemplo3_tableComDadosdoBanco.class.getName()).log(null, null, e111);             JOptionPane.showMessageDialog(null, e111);             e111.printStackTrace();         }catch (Exception e1111)         {             System.err.println("Got an exception! ");             System.err.println(e1111.getMessage());           }}         /**      * Create the frame.      */     public Certificados() {         setTitle("Selecione o Membro que emitir\u00E1 Carta");         setIconImage(Toolkit.getDefaultToolkit().getImage(Certificados.class.getResource("/icon/icon_igrejas.png")));         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         setBounds(100, 100, 465, 440);         contentPane = new JPanel();         contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));         setContentPane(contentPane);         contentPane.setLayout(null);         this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);                              ...Código...           btn_imprimir = new JButton("");         btn_imprimir.addActionListener(new ActionListener() {             public void actionPerformed(ActionEvent arg0) {                                       ...Código...                  try {                     geraPdf(txt_data.getText(), txt_Certificado.getText(), lbl_Dirigente.getText(), txt_prPresidente.getText(), txt_Mensagem.getText(), cb_assinatura.getSelectedItem().toString(), cb_prDirigente.getSelectedItem().toString(), txt_prDirigente.getText(), txt_titCertificado.getText());                  } catch (SQLException e) {                     // TODO Auto-generated catch block                     e.printStackTrace();                 }             }         });         btn_imprimir.setIcon(new ImageIcon(Certificados.class.getResource("/icon/printer icon40x40.png")));         btn_imprimir.setBounds(362, 326, 61, 50);         contentPane.add(btn_imprimir);                                      ...Código...                                   ...Código...          cb_assinatura.setBounds(31, 136, 176, 20);         contentPane.add(cb_assinatura);          cb_prDirigente = new JComboBox();         cb_prDirigente.addActionListener(new ActionListener() {             public void actionPerformed(ActionEvent arg0) {                 try {                     String sql = "select img_arc_dir FROM certificados";                     Connection con = Conexao.conectar();                     PreparedStatement prep = con.prepareStatement(sql);                     ResultSet rs = prep.executeQuery();                      int usertypes = (int) cb_prDirigente.getSelectedIndex();                      if(rs != null) {                         while(rs.next()) {                          switch (usertypes) {                         case 0:                              lbl_Dirigente.setIcon(null);                              this.dispose();                             break;                         case 1:                               byte[] imagedir= rs.getBytes("img_arc_dir");                                   if(imagedir != null) {                                ImageIcon formatdir = new ImageIcon(imagedir);                                 formatdir.setImage(formatdir.getImage().getScaledInstance(pn_dirigente.getWidth() -5, pn_dirigente.getHeight() -5, 100));                                lbl_Dirigente.setIcon(formatdir);                               this.dispose();                             break;                     }                  }             }                    }              prep.close();         }catch (SQLException e) {             e.printStackTrace();         }              }              private void dispose() {                 // TODO Auto-generated method stub              }         });         cb_prDirigente.setModel(new DefaultComboBoxModel(new String[] {"Selecione uma Rubrica", "Pastor Dirigente"}));         cb_prDirigente.setBounds(238, 136, 176, 20);         contentPane.add(cb_prDirigente);          pn_dirigente = new JPanel();         pn_dirigente.setBorder(new LineBorder(new Color(169, 169, 169)));         pn_dirigente.setBounds(231, 168, 192, 47);         contentPane.add(pn_dirigente);         pn_dirigente.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));          lbl_Dirigente = new JLabel("");         pn_dirigente.add(lbl_Dirigente);      } } 

Using blob to migrate Cosmos DB MongoDB server in Azure

I have a mongodb server running on Azure’s Cosmos DB service.

I have upload a mongodb dump in .bson format as a blob and named it as collection.database.bson, where collection and database are replaced.

Using the microsofts migration tutorial I get to the header “Specify source details” where we are asked to give a link to the source. I am using the connection string to my .bson blob. It goes through, however, I am met with an empty screen like this but nothing in the row.

I’ve tried linking to the contain the blob is in too, with no luck. Any ideas on how to make this work?

Blob trigger- not unzipping/detecting gif and png files

I have an azure function app which is a blob trigger. It detects new zip files in a container and extracts them to a new container. It is able to detect PDF, HTML files in the zip folder but cannot detect gif files, png files etc. Is there a different namespace/library/package I should use?

using System; using System.IO; using System.IO.Compression; using System.Linq; using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Host; using Microsoft.Extensions.Logging; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob;  namespace IV4.Function {     public static class iv4Unzipthis     {         [FunctionName("Unziptestiv4")]         public static async Task Run([BlobTrigger("input-files/{name}", Connection = "unzip_STORAGE")]Stream myBlob, string name, ILogger log)         {             log.LogInformation($  "C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");              string destinationStorage = Environment.GetEnvironmentVariable("destinationStorage");             string destinationContainer = Environment.GetEnvironmentVariable("destinationContainer");              try{                 if(name.Split('.').Last().ToLower() == "zip"){                      ZipArchive archive = new ZipArchive(myBlob);                      CloudStorageAccount storageAccount = CloudStorageAccount.Parse(destinationStorage);                     CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();                     CloudBlobContainer container = blobClient.GetContainerReference(destinationContainer);                      foreach (ZipArchiveEntry entry in archive.Entries)                     {                         log.LogInformation($  "Now processing {entry.FullName}");                          CloudBlockBlob blockBlob = container.GetBlockBlobReference(entry.Name);                         using (var fileStream = entry.Open())                         {                            await blockBlob.UploadFromStreamAsync(fileStream);                         }                     }                 }             }             catch(Exception ex){                 log.LogInformation($  "Error! Something went wrong: {ex.Message}");              }                     }     } }