图片显示

来源:互联网 发布:淘宝买家信用怎么提高 编辑:程序博客网 时间:2024/04/29 15:01

    将图片上传到阿里云服务器时,通过外网无法直接访问图片路径,这时就必须要通过IO流在界面上显示。

  

   在web.xml配置文件中加上:

  <servlet>
        <servlet-name>OSSReader</servlet-name>
        <servlet-class>action.OSSReader</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>OSSReader</servlet-name>
        <url-pattern>/img</url-pattern>                
    </servlet-mapping>


    界面中显示图片已

    <img src="<%=basePath %>/img?fileName=${fileName }" onload="javascript:if (this.width>121) this.width=121;if(this.height>121) this.height=121"/>


   OSSReader:

   public class OSSReader extends HttpServlet {

    private Logger log = LoggerFactory.getLogger(OSSReader.class);

    private static final long serialVersionUID = 4029716041969911408L;

    protected void service(HttpServletRequest request,
            HttpServletResponse response) throws ServletException,
            java.io.IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            String fileName = request.getParameter("fileName");
            log.debug("fileName=" + fileName);
            if (StringUtils.isBlank(fileName)) {
                fileName = "user_logo/default_logo.png";
            }
            is = downLoadFile(fileName);//从阿里云服务器获取IO流
            if (null != is) {
                response.setContentType("image/jpeg");
                os = response.getOutputStream(); // 创建输出流
                int c = 0;
                while ((c = is.read()) != -1) {
                    os.write(c);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

   /**
     *  这个方法可以写在阿里云公共方法中
     */

   public static InputStream downLoadFile(String fileName) throws Exception {
        log.info("downLoadFile start");
        InputStream fileStream = null;
        OSSClient client = null;
        try {
            // 创建上传客户端
            client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            OSSObject data = client.getObject(bucketName, fileName);
            fileStream = data.getObjectContent();
            log.info("get file " + fileName + "   success!");
            log.info("downLoadFile end");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
//            client.shutdown();
        }
        return fileStream;
    }

  
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        service(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        service(request, response);
    }
}


0 0