How to download byte[] array, stored in database, as a file?

We use Spring framework to develop our online system. Users now can upload their files. Data is stored in PostrgreSQL DB and associated with byte[] type attribute of a java class (through Hibernate). How can I perfom invert operation - transform a byte stream into a file and allow user to download it? Thanx

public void writeToFile(byte[] b, String directory, String filename) throws IOException {
   File outputFile = new File(directory, filename);
   OutputStream outputStream = new FileOutputStream(outputFile);
   outputStream.write(b);
   outputStream.close();
}

Similar Messages

  • How to add byte[] array based Image to the SQL Server without using parameter

    how to add byte[] array based Image to the SQL Server without using parameter.I have a column in table with the type image in sql and i want to add image array to the sql image column like below:
    I want to add image (RESIM) to the procedur like shown above but sql accepts byte[] RESIMI like System.Drowing. I whant that  sql accepts byte [] array like sql  image type
    not using cmd.ParametersAdd() method
    here is Isle() method content

    SQL Server binary constants use a hexadecimal format:
    https://msdn.microsoft.com/en-us/library/ms179899.aspx
    You'll have to build that string from a byte array yourself:
    byte[] bytes = ...
    StringBuilder builder = new StringBuilder("0x", 2 + bytes.Length * 2);
    foreach (var b in bytes)
    builder.Append(b.ToString("X2"));
    string binhex = builder.ToString();
    That said, what you're trying to do - not using parameters - is the wrong thing to do. Not only it is insecure due to the risk of SQL injection but in the case of binary data is also inefficient since these hex strings are larger than the original byte[]
    data.

  • I am new sto Lightroom and have also just changed from Apple to PC.  I cannot figure out how to download photos from the Photoshop library to a file that will be sent to MPIX for processing.  Also, does Lightroom have an easy access to a photo processing

    I am new to Lightroom and have also just changed from Apple to PC.  I cannot figure out how to download photos from the Photoshop library to a file that will be sent to MPIX for processing.  Also, does Lightroom have an easy access to a photo processing capability such as MPIX?

    Use the trackpad to scroll, thats what it was designed for. The scroll bars automatically disappear when not being used and will appear if you scroll up or down using the trackpad.
    This is a user-to-user forum and most people will post on here if they have problems. You very rarely get people posting to say there update went smooth. The fact is the vast majority of Mountain Lion users will not be experiencing any major problems with the OS, or maybe with apps which are not compatible, but thats hardly Apple's fault if developers don't update their apps.

  • Problem in reading/writing byte array in Access database! PLEASE HELP!!

    Hi,
    I want to store a signature, which is in form of a byte array, in OLE Object field in MS Access database. I want then to retrieve this signature and verify it. The problem is that the retrieved byte array is not identical to the stored (original) one, and therefore, verifying the signature fails! Any help would be much appreciated as I can't proceed in my project without solving this problem. Here is the code to do the above mentioned functionality:
    //This part stores the signature (VT) in the table TTPTrans
    try
    { con = connect();
    ps = con.prepareStatement("UPDATE TTPTrans SET VT = ?, SigVT = ? WHERE TransID = ?");
    ps.setBinaryStream(1, new ByteArrayInputStream(vt), vt.length);
    ps.setBinaryStream(2, new ByteArrayInputStream(sigvt), sigvt.length);
    ps.setString(3, tID);
    ps.executeUpdate();
    ps.close();
    con.close();
    catch (Exception e)
    {  System.err.println(e.getMessage());
    e.printStackTrace();
    //This part retrive the signature from the table in the byte array o1:
    ResultSet result;
    byte[] o1 = null;
    byte[] o2 = null;
    try
    { con = connect();
    Statement statement = con.createStatement();
    result = statement.executeQuery("SELECT VT, SigVT" +
    " FROM TTPTrans" +
    " WHERE TransID = " + "'" +
    transID + "'");
    while (result.next()) {
    o1 = result.getBytes("VT");
    o2 = result.getBytes("SigVT");
    statement.close();
    con.close();
    catch(Exception e)
    { System.err.println(e.getMessage());
    e.printStackTrace();
    }

    In the following code, I use a ASN1SDSSSignature class, which is a subclass that I created from the Siganture class, to create and verify an SDSS signature. The ASN1SDSSSignature has two ASN1Integer class variables:
    signcryption = token.getSigncryption();
    sig.initVerify(ttpCert);
    sig.update(receivedVT);
    boolean verified = sig.verify(receivedSigVT);
    if(!verified)
    System.err.println("TTP signatire on received token invalid. ");
    notify()
    return;
    Where receivedVT and receivedSigVT are the byte arrays retrieved from th database. The following exception is thrown when I run the application:
    ASN1 type mismatch!
    Expected: codec.asn1.ASN1Integer
    In: ASN1SDSSSignature
    At index 0
    Got tag: 4 and Class: 0
    I hope this would clarify the situation and thanks in advance for any comments you may post.

  • [Forum FAQ] How do i use xml stored in database as dataset in SQL Server Reporting Services?

    Introduction
    There is a scenario that users want to create SSRS report, the xml used to retrieve data for the report is stored in table of database. Since the data source is not of XML type, when we create data source for the report, we could not select XML as Data Source
    type. Is there a way that we can create a dataset that is based on data of XML type, and retrieve report data from the dataset?
    Solution
    In this article, I will demonstrate how to use xml stored in database as dataset in SSRS reports.
    Supposing the original xml stored in database is like below:
    <Customers>
    <Customer ID="11">
    <FirstName>Bobby</FirstName>
    <LastName>Moore</LastName>
    </Customer>
    <Customer ID="20">
    <FirstName>Crystal</FirstName>
    <LastName>Hu</LastName>
    </Customer>
    </Customers>
    Now we can create an SSRS report and use the data of xml type as dataset by following steps:
    In database, create a stored procedure to retrieve the data for the report in SQL Server Management Studio (SSMS) with the following query:
    CREATE PROCEDURE xml_report
    AS
    DECLARE @xmlDoc XML;  
    SELECT @xmlDoc = xmlVal FROM xmlTbl WHERE id=1;
    SELECT T.c.value('(@ID)','int') AS ID,     
    T.c.value('(FirstName[1])','varchar(99)') AS firstName,     
    T.c.value('(LastName[1])','varchar(99)') AS lastName
    FROM   
    @xmlDoc.nodes('/Customers/Customer') T(c)
    GO
    P.S. This is an example for a given structured XML, to retrieve node values from different structured XMLs, you can reference here.
    Click Start, point to All Programs, point to Microsoft SQL Server, and then click Business Intelligence Development Studio (BIDS) OR SQL Server Data Tools (SSDT). If this is the first time we have opened SQL Server Data Tools, click Business Intelligence
    Settings for the default environment settings.
    On the File menu, point to New, and then click Project.
    In the Project Types list, click Business Intelligence Projects.
    In the Templates list, click Report Server Project.
    In Name, type project name. 
    Click OK to create the project. 
    In Solution Explorer, right-click Reports, point to Add, and click New Item.
    In the Add New Item dialog box, under Templates, click Report.
    In Name, type report name and then click Add.
    In the Report Data pane, right-click Data Sources and click Add Data Source.
    For an embedded data source, verify that Embedded connection is selected. From the Type drop-down list, select a data source type; for example, Microsoft SQL Server or OLE DB. Type the connection string directly or click Edit to open the Connection Properties
    dialog box and select Server name and database name from the drop down list.
    For a shared data source, verify that Use shared data source reference is selected, then select a data source from the drop down list.
    Right-click DataSets and click Add Dataset, type a name for the dataset or accept the default name, then check Use a dataset embedded in my report. Select the name of an existing Data source from drop down list. Set Query type to StoredProcedure, then select
    xml_report from drop down list.
    In the Toolbox, click Table, and then click on the design surface.
    In the Report Data pane, expand the dataset we created above to display the fields.
    Drag the fields from the dataset to the cells of the table.
    Applies to
    Reporting Services 2008
    Reporting Services 2008 R2
    Reporting Services 2012
    Reporting Services 2014
    Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.

    I have near about 30 matrics. so I need a paging. I did every thing as per this post and it really works for me.
    I have total four columns. On one page it should show three and the remaining one will be moved to next page.
    Problem occurs when in my first row i have 3 columns and in next page if I have one columns then it show proper on first page but on second page also it gives me three columns insted of one. the first column data is exactly what I have but in remaining two
    columns it shows some garbage data.
    I have data like below.
    Metric ColumnNo RowNo
    1 1
    1
    2 2
    1
    3 3
    1
    4 1
    2
    so while grouping i have a row parent group on RowNo and Column group on ColumnNo.
    can anyone please advice on this.

  • How to get byte array from jpg in resource for Image XObject?

    Hi,
    Does anyone know how to get an array of bytes from a jpg from resource without an external library except MFC?
    The array of bytes is needed to create an Image XObject so it can be included in an appearance for an annotation.

    Sounds like a standard Windows programming question, not specific to the SDK.

  • How to save Byte Array of raw data into JPEG image.

    Hello!
    I have a image and I stored its data as byte array as
    bimage = bitmap1.getRawData();
    now I have Byte[] bimage, I want to save it as .jpeg image.
    and show that image..............

    the short way is this:
    ImageIO.write(bimage, "jpeg", new File("image.jpg"));
    Where you use the original Image object... but it has to be a java.awt.image.RenderedImage (which a java.awt.image.BufferedImage is). So this method would come in handy.
         public static BufferedImage getBufferedImage(Image img) {
              // if the image is already a BufferedImage, cast and return it
              if((img instanceof BufferedImage) && background == null) {
                   return (BufferedImage)img;
              // otherwise, create a new BufferedImage and draw the original
              // image on it
              int w = img.getWidth(null);
              int h = img.getHeight(null);
              BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g2d = bi.createGraphics();
              g2d.drawImage(img, 0, 0, w, h, null);
              g2d.dispose();
              return bi;
         }If the byte array you have is raw image data, then you can look at the javax.imageio package and see what you can do with those classes.

  • How to encrypt byte array with out padding using RSA in Java?

    I've modulus and public exponent as byte[] array, so I'm trying to convert into BigIntegers and then create public key and then Cipher. Here is the example code:
    With this I'm always getting different encrypted bytes, is it because of padding. I dont want to use any padding so what parameter I need to pass along with RSA? I've modulus byte[] array size 64 bytes. I believe I'll get 64 encrypted bytes. I've content size of 32 bytes to be encrypted.
    --------code begin ---------------------------
    BigInteger bexponent = new BigInteger(pubExpo);
    BigInteger bmodulus = new BigInteger(modulus);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(bmodulus, bexponent);
    RSAPublicKey pubKey = (RSAPublicKey)keyFactory.generatePublic(pubKeySpec);
    Cipher c = Cipher.getInstance("RSA");
    c.init(Cipher.ENCRYPT_MODE, pubKey);
    return c.doFinal(content);
    --------code end---------------------------

    With this I'm always getting different encrypted
    bytes, is it because of padding. Yes, if you're using PKCS1Padding (which is the default in SunJCE if you don't specify it). Have a look at the PKCS1 spec if you haven't seen it already.
    http://www.rsasecurity.com/rsalabs/pkcs
    Section 7.2.1 talks about type 2 padding, which uses random bytes as the PS string.
    I dont want to use
    any padding so what parameter I need to pass along
    with RSA? NOPADDING. You should be able to find this out by look at the "Supported Paddings" parameter in your provider's database. Which of course, means you'll need to supply the right number of bytes to the Cipher.

  • How Convert a Byte array to a image format

    Hi,
    How to convert a Byte array to an image format....I shall be more clear what i want...See i recieve a Byte array fom server this Byte array before recieveing at my end it was converted from an image/text format into a Byte array and is sent from server and, I recieve this Byte array now I have to convert this Byte array into their respective image....please tell me how to convert a Byte array to a image ......... Kindly explain clearly as i am new to Java......
    Thanking You.

    Note: This thread was originally posted in the [New To Java|http://forums.sun.com/forum.jspa?forumID=54] forum, but moved to this forum for closer topic alignment.

  • How to send byte array and String values to servlet from Swing application

    Hi all,
    I am new to swing, servlet, and socket connection.
    I have swing application to draw images and some input data. I dont know to send to server.
    byte[] buf = baos.toByteArray();
    URL servletURL = new URL("http://10.70.70.1:8080/servlet/SaveImage)
    URLConnection conn = servletURL.openConnection();
    conn.setDoOutput(true);
    BufferedWriter out = new BufferedWriter( new OutputStreamWriter( conn.getOutputStream() ) );
    out.write(buf&a=aaaa&b=bbbbb);
    out.flush();
    out.close();
    can I do like this. Strings are received in server side perfect. but i cant get byte array data. Please help me.
    Thanks in advance.

    <img src="myservlet">
    In your myservlet:
    response.setContentType("image/jpeg");
    then write your image date via ImageIO that uses response output stream.

  • How to pass byte array / binary data to a webservice as parameter in osb

    i have a webservice that has a byte array input parameter. i tried to use this WS in a message flow via service-callout. the problem i encountered is the following: since webservice call by using service-callout requires you to use an xml input as part of soap message, i insert both of $body/ctx:binary-content and $body/ctx:binary-content/@ref variables individually into this xml-message to pass binary-data to WS. When i debug the code, i see that it make calls to WS with $body/ctx:binary-content/@ref parameter, but the byte array passed is empty(not NULL)...
    note: i tried java-callut instead of service-called and used $body/ctx:binary-content as input parameter it worked. i think, this is because java-callout doesnt need an xml input and enable to take variables as is...
    can anybody help me to solve the problem with service-callout please?
    here is the input i use to call ws with service-callout method...
    <iso2Xml xmlns="http://www.mycompany.com.tr">
    <request>{$body/ctx:binary-content/@ref}</request>
    </iso2Xml>
    and this is my WS's signature:
    @WebMethod
    public String iso2Xml(byte[] request)

    Hi
    See this thread
    /message/2187817#2187817 [original link is broken]
    Kind Regards
    Mukesh

  • How to send byte array of image with 300dpi.

    Hello fiends
                       i am making an application in which i have to send the byte array of an image with 300dpi.
    so i am using image snapshot class for that and use that code.
                        var snapshot:ImageSnapshot = ImageSnapshot.captureImage(cnvParent,300);
                        var bdata:String = ImageSnapshot.encodeImageAsBase64(snapshot);
    but when i send that bdata to php end using httpService.The size at other end of image increases surprisingly.i means it will increase its actual height and actual width.so is there any way to overcome this increase in size when i bitmapped image at 300 dpi?
    if there any way then please tell me.waiting for your reply.
    Thanks and Regards
        Vineet Osho

    Thanks david for such a quick reply.the link is really helpful.So we have to calculate the screendpi thruogh our code and then set the height and width of image.is there any simple way to sort out my problem.i just want to print my image at 300dpi but i am using image snapshot class so its taking the snap of my container(image) and save the image at 96 dpi which is dpi of my screen(monitor).so is there any way or any class in flex through which i got the image at its original dpi.i am not stick on 300 dpi but i m getting image from backend through xml at 300dpi.thats why i want the byte array i am sending should be at 300dpi.i am totally confused now.so please help me.
    Thanks and regards
      Vineet osho

  • How to download a java class from database to file system

    Hi All,
    We have one invalid java class in database. We need to verify what is the functionality of this class. So we planned to download this class to file system. Then we need decompile it to source. But we are not able to identify the right command to download the java class from database.
    Please suggest me if any possible ways to acheive this.
    Thanks in advance....

    http://www.sql.ru/forum/actualthread.aspx?tid=747308
    http://download.oracle.com/docs/cd/B19306_01/java.102/b14187/appendixa.htm
    PROCEDURE export_source(name VARCHAR2, schema VARCHAR2, blob BLOB)
    PROCEDURE export_class(name VARCHAR2, schema VARCHAR2, blob BLOB)
    PROCEDURE export_resource(name VARCHAR2, schema VARCHAR2, blob BLOB)
    create table scott.t (id number, b blob);
    declare      
        b blob;
        begin
           dbms_lob.createTemporary(b, true, dbms_lob.CALL);
           dbms_java.export_class('sun/net/www/ParseUtil', user, b);
          dbms_output.put_line('length(b): '||length(b));
          insert into "SCOTT"."T" values(1,b);
        end;

  • Sound file storing in Database &  accessing these files

    Hi Friends
    i have working on the project of Sound Recognization system
    the requirement is that sound should be passed through mike input device & that sound should be stored in to database along with the user & password
    for recognization & identification of user
    But problem in storing the sound files in the database so how can i store the files into the database so please guide me.

    brad103 wrote:
    In my particular application, I process the byte array from the TargetDataLine. Then I save this to a db using new ByteArrayInputStream(soundData), soundData.length); where soundData is my byte[].
    Am I correct that this will save the data in the relevant format (eg PCM_SIGNED, 8k, 16bit, etc), but the header information is not included? That's correct. Essentially, in JavaSound, that data has an associated "Format" object that was part of the line the data came from, would need to be given to any line the data was going to...and that format object is essentially a container for all of the header data...
    And if so, then if I control the saving and retrieval then I can omit that step anyway as I know the format?You can omit the AudioSystem.write step and store the byte[] directly into the database...as long as you're capable of, as above, recreating the Format object that was originally associated with the data.
    And my next question (digressing slightly, sorry umeshS), is that when using the tritonus gsm library and converting from above format to gsm, should I be using AudioSystem.write to write to an outputstream prior to calling AudioSystem.getAudioInputStream(targetEncoding, originalAIS) to convert encodings?AudioSystem.write adds the file header to the stream, and that's all. If you're using a "stream", you have to have the Format object in order to create an AudioInputStream, so there's no need to add the file header (and the file header will screw things up if you're not using the File or URL versions of getAudioInputStream)...
    So, as a giant summary...
    AudioSystem.write adds a file header, which will include format information. This should only be used if you're planning on using AudioSystem.getAudioInputStream(File f) to read the file the next time.
    Otherwise, just save the data and the Format object associated with the data, so you can read it all back in later by building an AudioInputStream around your favorite IO stream.
    And in retrospect, after explaining all of that...umeshS, the problem with the way you're doing it is that when you copy the file into the database, you're copying the file header. And then, because you're not using the "File" version of AudioSystem.getAudioInputStream, the system isn't handling the file header being there correctly.
    You need to copy things into the database by creating an audioinputstream of your file, and then saving out the raw byte[] data. You can just call "read" on the ais a bunch of times and throw the results into your stream. Then, you can play it by pulling the data out of the database via a stream, and playing that stream by throwing it back into an AudioInputStream.

  • How to Print Bytes[] from a resultset in a text file? Thanks a Lot!!

    Hi all I'm having a prb in printing the Byte[] from a Resultset in a textfile . Every time I exceute this program different values is printing in the text file and in binary format like:
    [B@29c3,[B@347a,[B@3f2f,[B@49e6,[B@549d
    and I'm supposed to get the out put as :
    0000690D,00002107,00009F16,00003008,0000ED0F
    Here is the sample code!
    public static void main(String[] args) {
         try {
    Class.forName(drvName);
    Connection con = DriverManager.getConnection(url, SDR_userName, SDR_passWord);
    Statement stmt = con.createStatement();
    int count1 = 0;
    char c = 'c';
    ResultSet rs1 = stmt.executeQuery(_sqlQuery);
    FileOutputStream fos = new FileOutputStream(inputFileName);
    Writer out = new OutputStreamWriter(fos, "UTF8");
    while (rs1.next()) {
    byte[] _id = rs1.getBytes(1);
    String _name = rs1.getString(2);
    out.write("_id=="+id+"==name=="+_name);
    int len = sales_account_id.length;
    System.out.println("Length==" + len);
    String s = new String(_id, 0, len, "UTF8");
    char c1[] = s.toCharArray();
    for (int i = 0; i < s.length(); i++) {
    System.out.print("s1" + c1);
    System.out.println("_Id" + s.toString());
    try {
    for (int i = 0; i < len; i++) {
    c = (char) _id;
    System.out.println("_Id" + c);
    catch (Exception statemets...){}
    Thanks a lot in advance!!

    out.write("_id=="+id+"==name=="+_name);
    in this line you are printing the array _id. when you do that ( print array ) you get the address of that array. so the output is expected.
    what you can do is create a new String from the byte array and write that string to the file.
    String temp = new String( _id );
    out.write("_id=="+temp+"==_name=="+_name);
    hope i got your problem right

Maybe you are looking for

  • Perform Post Goods Receipt Against Scheduling Agreement

    Dear all, I've weird problem here. This is concering GR against Scheduling Agreement. I've a "LPA" type Scheduling Agreement and all the delivery schedule maintained and schedule line released successfully in ME38. When I do GR via MIGO by entering t

  • Agent Registration Issue

    I sent an Agent an invite and when they signed up, it created their own account vs being able to approve under my On Plus account.  How do I resolve this?                  

  • SAPSCRIPT - print of scanned text

    Hi Guys, I have the following problem: We would like to print the scanned signatures of 2 persons at a orderform (sales order). The form is an sapscript form. For every sales order we have 2 persons which are responsible. Now we would like to print t

  • Anyone having issues using autoplay to import photos from an iPhone 4S?

    I haven't been able to import photos for days using autoplay. Every time I connect my phone autoplay recognizes it but won't let me select an option. It's non-responsive. Anyone else?  Any solutions?

  • Cannot open adobe reader x online

    When I try to open a workbook pdf file on my store builder online, either a blank screen comes up, a download strip which goes nowhere, or a box which says there is a problem with your adobe acrobat/reader.  If it is open, close it and try again.  We