springmvc上传图片的处理

/**
*上传请求方法springmvc上传图片(有还是(在没有返回值时默认none))的处理
*@param myfilename
*/
@RequestMapping(value = "/uploadresouce", method = RequestMethod.POST)@ResponseBodypublic String doUploadMyResouce( @RequestParam(value = "myfilename", required = false,
defaultValue = ValueConstants.DEFAULT_NONE) MultipartFile myfilename){
/
 /**文件原名**/
    String imageName = "";
    /**新文件名称由当前项目路径和上传文件路径和文件后缀名组成**/
    String filePath = "";
    /**上传成功与否标示符**/
    String returninfo = "error";
    /**构建图片保存的目录**/
    String logoPathDir = "/WEB-INF/Upload";
    /**得到图片保存目录的真实路径**/
    String logoRealPathDir = request.getSession().getServletContext().getRealPath(logoPathDir);
    if (color_icon == null) {
      /**没有上传图片文件**/
this.myservice.doUpload(""); returninfo =GlobalConfig.SUCCESS; } else { String logImageName = color_icon.getOriginalFilename(); //检查文件后缀是否符合图片类型 boolean checkFileType = FileUtil.checkFileType(logImageName, true); //判断上传文件是否是图片 boolean isImg = this.isimg(color_icon); if (checkFileType && isImg) { //文件原名 imageName = color_icon.getOriginalFilename(); //新文件名称由当前项目路径和上传文件路径和文件后缀名组成 //UUID)加密名称 filePath = String.valueOf(UUID.randomUUID().toString().replaceAll("-", "") + "." + imageName.split("\\.")[1]); //构建图片保存的目录logoRealPathDir String urlimage = logoRealPathDir + "\\" + filePath;
            this.myservice.doUpload(urlimage );
            //根据真实路径创建目录
            File logoSaveFile = new File(logoRealPathDir);
            //是否新建保存文件夹
            if (!logoSaveFile.exists()) {
                logoSaveFile.mkdirs();
            }
            //上传文件
            SaveFileFromInputStream(color_icon.getInputStream(), logoRealPathDir, filePath);
            returninfo =GlobalConfig.SUCCESS;
        }
    }
    return returninfo;
}
------------------------------------------------------------------------------------
/**
 * 上传文件
 *
 * @param is
 * @param path
 * @param filePath
 * @throws IOException
 */
public void SaveFileFromInputStream(InputStream is, String path, String filePath) throws IOException {
    FileOutputStream fs = new FileOutputStream(path + "/" + filePath);
    byte[] buffer = new byte[1 * 1024];
    int byteread = 0;
    while ((byteread = is.read(buffer)) != -1) {
        fs.write(buffer, 0, byteread);
        fs.flush();
    }
    fs.close();
}

/**
 * 判断上传的文件是否为图片
 *
 * @param multipartFile
 * @return
 */
public static boolean isimg(MultipartFile multipartFile) {

    InputStream is = null;
    try {
        is = multipartFile.getInputStream();
        byte[] bt = new byte[2];
        is.read(bt);
        // 获取16进制文件头
        String hex = new BytesUtil().bytesToHexString(bt);
        String fileType = FileUtil.getFileType(multipartFile.getOriginalFilename());
        // 判断图片对应的16进制头
        if (fileType.equals(".jpg")) {
            if (hex.equals("ffd8")) {
                return true;
            }
        }
        if (fileType.equals(".gif")) {
            if (hex.equals("4749")) {
                return true;
            }
        }
        if (fileType.equals(".png")) {
            if (hex.equals("8950")) {
                return true;
            }
        }
        if (fileType.equals(".bmp")) {
            if (hex.equals("424d")) {
                return true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return false;
}
-------------------------------------------
FileUtil,BytesUtil工具类
-----------------------------------------
-----------------FU----------
public class FileUtil {
    /**允许上传的图片类型**/
    public static final String IMG_TYPE = ".jpg|.gif|.png|.bmp";
    /**允许上传的所有文件类型**/
    public static final String ALL_TYPE = ".jpg|.jepg|.gif|.png|.bmp|.gz|.rar|.zip|.pdf|.txt|.swf|.mp3|.jar|.apk|.ipa";

    /**
     * 检测文件大小
     * @param file 文件
     * @param kb 限制大小
     * @return true 超过限制
     */
    public static boolean checkFileSize(File file, int kb){
        long size = file.length();
        if (size > 1024 * kb) {
            return true;
        }
        return false;
    }

    /**
     * 检查文件类型
     * @param fileName 文件名
     * @param isImg 是否检查图片
     * @return true=后缀合法
     * @throws
     */
    public static boolean checkFileType(String fileName, boolean isImg) {
        String fileType = getFileType(fileName);
        if (isImg) {
            return IMG_TYPE.indexOf(fileType.toLowerCase()) != -1;
        } else {
            return ALL_TYPE.indexOf(fileType.toLowerCase()) != -1;
        }
    }

    /**
     * 获取文件类型
     * @param fileName
     * @throws
     */
    public static String getFileType(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."), fileName.length());
    }

    public static void main(String[] args) {
        String s = getFileType("12321.jpg");
        System.out.println(s);
    }
}

----------------BU----------
public class BytesUtil {
    /**
     * Convert byte[] to hex string. 把字节数组转化为字符串
     * 这里我们可以将byte转换成int,然后利用Integer.toHexString(int)来转换成16进制字符串。
     * @param src byte[] data
     * @return hex string
     */
    public static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv+"");
        }
        return stringBuilder.toString();
    }
    /**
     * Convert hex string to byte[]   把为字符串转化为字节数组
     * @param hexString the hex string
     * @return byte[]
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }
    /**
     * Convert char to byte
     * @param c char
     * @return byte
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
}
-------------页面---------
<form  method="POST" enctype="multipart/form-data" 
class="form-horizontal" id="UploadForm" name="UploadForm">
<input type="file" id="myfilename" name="myfilename" >


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值