关闭

图片的上传和预览(上传到oracle数据库)

标签: java
302人阅读 评论(0) 收藏 举报
分类:

注意:

1.数据库字段使用clob存储

2.实体类中使用byte数组存图片流

3.图片预览以流的形式输出

文件上传下载预览辅助类代码:

package com.yuanxin.app.appkmbgszh.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

public class FileUtil {

    public static List<byte[]> upload(HttpServletRequest request) {
        List<byte[]> ret = new ArrayList<byte[]>();
        try {
            // 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession()
                    .getServletContext());
            // 检查form中是否有enctype="multipart/form-data"
            if (multipartResolver.isMultipart(request)) {
                // 将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                // 获取multiRequest 中所有的文件名
                Iterator iter = multiRequest.getFileNames();
                InputStream is = null;
                while (iter.hasNext()) {
                    // 一次遍历所有文件
                    MultipartFile file = multiRequest.getFile(iter.next().toString());
                    if (file != null) {
                        is = file.getInputStream();
                        byte[] bytes = FileCopyUtils.copyToByteArray(is);
                        ret.add(bytes);

                        /*  SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHssmm");
                          Date date = new Date();
                          String subfix = file.getOriginalFilename().substring(
                                  file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
                          String path1 = path + sdf.format(date) + "." + subfix;
                          result.put("fileName", file.getOriginalFilename());
                          result.put("path", path1);
                          // 上传
                          // 创建目录
                          File fp = new File(path1);
                          if (!fp.exists()) {
                              // 目录不存在的情况下,创建目录。
                              fp.mkdirs();
                          }
                          file.transferTo(fp);*/
                    }

                }

            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return ret;
    }

    public static void downloadFile(HttpServletResponse response, String path, String fileName) {
        try {
            URL url = new URL(path);
            URLConnection con = url.openConnection();
            con.setConnectTimeout(5000);
            con.setReadTimeout(5000);
            //  File file = new File(path);
            // 以流的形式下载文件。
            InputStream is = con.getInputStream();
            //InputStream is = url.openStream(); 
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            is.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename="
                    + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
            response.addHeader("Content-Length", "" + buffer.length);
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("multipart/form-data");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    public static void showPhoto(HttpServletResponse response, byte[] photo) {
        response.setContentType("image/*");
        OutputStream toClient = null;
        try {
            toClient = response.getOutputStream();
            toClient.write(photo);
            toClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

controller中控制代码:

//上传图片
 @RequestMapping(value = "/headPortraitUpload", method = { RequestMethod.POST, RequestMethod.GET })
    @ResponseBody
    public Map<String, Object> headPortraitUpload(HttpServletRequest request, @Param("userCode") String userCode) {
        LOGGER.info("有访问来自,IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOGGER.info("userCode %s", userCode);
        Map<String, Object> ret = new HashMap<String, Object>();
        if (StringUtils.isBlank(userCode)) {
            ret.put("success", false);
            ret.put("msg", "userCode不能为空");
        }
        try {
            List<byte[]> streams = FileUtil.upload(request);
            if (streams != null && streams.size() > 0) {
                User user = userService.getByCode(userCode).getData();
                UserPhotoAO userPhotoAO = new UserPhotoAO();
                userPhotoAO.setId(user.getId());
                userPhotoAO.setUserCode(user.getCode());
                userPhotoAO.setUserName(user.getName());
                userPhotoAO.setPhoto(streams.get(0));
                userPhotoService.saveOrUpdateUserPhotoAO(userPhotoAO, userCode);
                ret.put("success", true);
                ret.put("msg", "上传成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            ret.put("success", false);
            ret.put("msg", "上传失败");
        }

        return ret;
    }

    /**
     * 头像显示
     * @param request
     * @param response
     * @param userCode
     */
    @RequestMapping(value = "/showPhoto")
    public void showPhoto(HttpServletRequest request, HttpServletResponse response, @Param("userCode") String userCode) {
        LOGGER.info("有访问来自,IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOGGER.info("userCode %s", userCode);
        UserPhoto userPhoto = userPhotoService.getUserPhotoAO(userCode);
        if (userPhoto != null) {
            FileUtil.showPhoto(response, userPhoto.getPhoto());
        } else {
            UserPhoto userPhoto1 = userPhotoService.getUserPhotoAO("admin");
            FileUtil.showPhoto(response, userPhoto1.getPhoto());
        }

    }

实体字段:

  private byte[] photo;




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:3621次
    • 积分:192
    • 等级:
    • 排名:千里之外
    • 原创:16篇
    • 转载:3篇
    • 译文:0篇
    • 评论:0条
    文章分类