Blob 轉 OutputStream

StreamingOutput.javajava

import java.io.IOException;
import java.io.OutputStream;

import javax.ws.rs.WebApplicationException;

/**
 * A type that may be used as a resource method return value or as the entity
 * in a {@link Response} when the application wishes to stream the output.
 * This is a lightweight alternative to a
 * {@link javax.ws.rs.ext.MessageBodyWriter}.
 *
 * @author Paul Sandoz
 * @author Marc Hadley
 * @see javax.ws.rs.ext.MessageBodyWriter
 * @see javax.ws.rs.core.Response
 * @since 1.0
 */
public interface StreamingOutput {

    /**
     * Called to write the message body.
     *
     * @param output the OutputStream to write to.
     * @throws java.io.IOException if an IO error is encountered
     * @throws javax.ws.rs.WebApplicationException
     *                             if a specific
     *                             HTTP error response needs to be produced. Only effective if thrown prior
     *                             to any bytes being written to output.
     */
    void write(OutputStream output) throws IOException, WebApplicationException;
}

轉化方法app

//經過患者ID查詢照片信息
@Override
public StreamingOutput getPatientPhotoByPatientId(String patientId) {
    //獲取患者信息裏面包含blob類型的照片和指紋信息
    PatInfoNote patInfoNote = strictFindByPrimaryKey(PatInfoNote.class, patientId, "未找到指定患者資料信息patientId");
    if (patInfoNote.getPatientPhotograph() == null) {
        throw new NotFoundException(String.format("患者照片信息不存在patientId[%s]", patientId));
    }
    StreamingOutput streamingOutput = null;
    try {
        //轉化方法
        streamingOutput = StringUtils.getStreamingOutputByBlob(patInfoNote.getPatientPhotograph());
    } catch (SystemException e) {
        throw new SystemException("讀取患者照片失敗");
    }
    return streamingOutput;
}
//-------
public static StreamingOutput getStreamingOutput(final InputStream in) throws IOException {
    StreamingOutput stream = new StreamingOutput() {
        public void write(OutputStream out) throws IOException, WebApplicationException {
            try {
                int read = false;
                byte[] bytes = new byte[1024];

                int readx;
                while((readx = in.read(bytes)) != -1) {
                    out.write(bytes, 0, readx);
                }

            } catch (Exception var4) {
                throw new IOException("文件流讀取失敗: " + var4.getMessage(), var4);
            }
        }
    };
    return stream;
}

public static StreamingOutput getStreamingOutputByBlob(Blob blob) throws RuntimeException {
    StreamingOutput streamingOutput = null;

    try {
        streamingOutput = getStreamingOutput(blob.getBinaryStream());
        return streamingOutput;
    } catch (Exception var3) {
        throw new RuntimeException("讀取數據流失敗", var3);
    }
}
相關文章
相關標籤/搜索