根据图片地址读取图片文件

/**   
 * @Title: ImageController.java 
 * @Description: TODO
 * @author zhangyd-c 
 * @date 2015年8月18日 下午1:04:15 
 * @version 1.0 
 */

package com.gcj.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *
 * @Description
 * @author (作者) zhangyd-c
 * @date (开发日期) 2015年8月18日 下午1:04:15
 * @version (版本) V1.0
 * @since (该版本支持的JDK版本) : 1.7
 * @modify (修改)
 * 
 * @Review (审核人)
 */
@Controller
@RequestMapping("/image")
public class ImageController {
    
    /**
     * 根据头像地址,读取头像文件
     * 
     * @param request
     * @param response
     * @param path
     * @author zhangyd-c
     * @date 2015年5月28日 上午9:21:02
     * @return void
     * @throws
     */
    @RequestMapping("/getUserAvatar")
    public void getUserLogo(HttpServletRequest request, HttpServletResponse response, String path) {
        File file = new File(path); // 括号里参数为文件图片路径
        if (!file.exists()) { // 如果文件不存在,则使用默认的图片
            path = request.getSession().getServletContext().getRealPath("/") + "assets/img/gallery/image2.jpg";// 可指定项目内的任意图片文件
            file = new File(path); // 括号里参数为文件图片路径
        }
        readyImage(response, file);
    }
    
    /**
     * 读取文件
     * 
     * @Description
     * @author zhangyd-c
     * @date 2015年10月10日 下午2:01:49
     * @param response
     * @param file
     */
    public void readyImage(HttpServletResponse response, File file) {
        response.setContentType("image/jpeg"); // 设置返回内容格式
        InputStream in = null;
        OutputStream os = null;
        try {
            in = new FileInputStream(file);
            os = response.getOutputStream(); // 创建输出流
            byte[] b = new byte[1024];
            while (in.read(b) != -1) {
                os.write(b);
            }
            os.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            
        }
    }
    
}

 应用场景:

    1.上传头像后根据头像地址读取头像文件用于前台显示

    2.图片预览

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智布道

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值