首页 > 代码库 > 5_1_图片上传

5_1_图片上传

图片上传

一 需求

1 图片上传到本地;

2 图片上传到七牛云。

  效果图:

  技术分享

 

二 具体代码实现

1 ToutiaoUtil.java: 用来判断上传的文件名是否合格;

package com.nowcoder.util;

import com.alibaba.fastjson.JSONObject;
import com.nowcoder.controller.LoginController;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.util.Map;

/**
 * Created by nowcoder on 2016/7/3.
 */
public class ToutiaoUtil {
    private static final Logger logger = LoggerFactory.getLogger(ToutiaoUtil.class);

    private static String[] IMAGE_FILE_EXT = {"png", "bmg", "jpg", "jpeg"};
    public static String IMAGE_DIR = "H:/toutiao/upload/";
    public static String IMAGE_DOMAIN = "http://192.168.0.100:8080/";

    public static boolean isAllowed(String fileExt) {

        if (fileExt == null) {
            return false;
        }

        for (String ext : IMAGE_FILE_EXT) {
            if (ext.equals(fileExt)) {
                return true;
            }
        }
        return false;
    }

}

2. NewsService.java : saveImage() 上传到本地:

/**
     * 上传到本地
     * @param file
     * @return
     * @throws IOException
     */
    public String saveImage(MultipartFile file) throws IOException{

        String fileOriName = file.getOriginalFilename();
        int dotPos = fileOriName.lastIndexOf(".");
        if(dotPos < 0){
            return  null;
        }
        String fileExt= fileOriName.substring(dotPos + 1).toLowerCase();
        if(!ToutiaoUtil.isAllowed(fileExt)){
            return null;
        }
        String fileNewName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
        Files.copy(file.getInputStream(), new File(ToutiaoUtil.IMAGE_DIR + fileNewName).toPath(),
                StandardCopyOption.REPLACE_EXISTING);
        return ToutiaoUtil.IMAGE_DOMAIN + "image?name= " + fileNewName;

    }

 

上传到七牛云:

package com.nowcoder.service;

import com.alibaba.fastjson.JSONObject;
import com.nowcoder.util.ToutiaoUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * Created by Administrator on 2017/4/20.
 */
@Service
public class QiniuService {
    private static final Logger logger = LoggerFactory.getLogger(QiniuService.class);
    //设置密钥私钥
    private static final String ACCESS_KEY = "F1gWSjirYuPH6tlHmWMmTKj6Vf-o_Zv-neyhsnX7";
    private static final String SECRET_KEY = "5IGLFKGyGtp_ZM2yBLFTSMFHNxVJF4H2JG4fRckv";
    //外链默认域名
    private static final String QINIU_DOMAIN_PREFIX= "http://oopscdse9.bkt.clouddn.com/";
    //设置上传空间
    String bucketName = "nowcoder";

    //密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    String upToken = auth.uploadToken(bucketName);
    //创建上传对象
    Configuration cfg = new Configuration(Zone.zone2());
    UploadManager uploadManager = new UploadManager(cfg);

    public String saveImage(MultipartFile file) throws IOException{
        try {
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            if(dotPos < 0){
                return null;
            }
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            if(!ToutiaoUtil.isAllowed(fileExt)){
                return null;
            }
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;

            //调用put方法上传
            Response response = uploadManager.put(file.getBytes(), fileName, upToken);

            System.out.print(response.bodyString());//{"hash":"FlzkXRBfIIpQh1JhBzIEMdfJzOr1","key":"20a0ed3733f84b8585da08b6277cd60a.jpg"}
            System.out.print(response.toString());
            if(response.isOK() && response.isJson()){
                String key = JSONObject.parseObject(response.bodyString()).get("key").toString();
                return QINIU_DOMAIN_PREFIX + key;
            }else {
                logger.error("七牛异常" + response.bodyString());
                return null;
            }
        }catch (QiniuException ex){
            Response r =  ex.response;
            logger.error("读取图片错误:" + ex.getMessage());
            System.out.print(r.toString());
            return null;
        }
    }






}

 

 

 

 

3. Controller : NewsController.java

  注:fileUrl可以随意切换,如上传到本地就得到一个本地的url;

                                          上传到七牛云就用七牛云的service得到一个url;

               上传到又拍云就用又拍云的service得到一个url.

@RequestMapping(value = http://www.mamicode.com/{"/uploadImage"}, method = {RequestMethod.POST})
    @ResponseBody
    public String uploadImage(@RequestParam("file") MultipartFile file){
        try {
            String fileUrl = newsService.saveImage(file);
            //String fileUrl = qiniuService.saveImage(file);
            if(fileUrl == null){
                return ToutiaoUtil.getJSONString(1, "图片上传失败");
            }
            return ToutiaoUtil.getJSONString(0, fileUrl);
        }catch (Exception e){
            logger.error("上传图片失败" + e.getMessage());
            return ToutiaoUtil.getJSONString(1, "图片上传失败");
        }
    }

 

如果上传到七牛云,就改成:

String fileUrl = qiniuService.saveImage(file);

 

相关的code:

package com.nowcoder.util;

import com.alibaba.fastjson.JSONObject;
import com.nowcoder.controller.LoginController;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.util.Map;

/**
 * Created by nowcoder on 2016/7/3.
 */
public class ToutiaoUtil {
    private static final Logger logger = LoggerFactory.getLogger(ToutiaoUtil.class);

    private static String[] IMAGE_FILE_EXT = {"png", "bmg", "jpg", "jpeg"};
    public static String IMAGE_DIR = "H:/toutiao/upload/";
    public static String IMAGE_DOMAIN = "http://192.168.0.100:8080/";

    public static boolean isAllowed(String fileExt){

        if(fileExt == null){
            return false;
        }

        for(String ext : IMAGE_FILE_EXT){
            if(ext.equals(fileExt)){
                return true;
            }
        }
        return false;
    }

    public static String getJSONString(int code){

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        return jsonObject.toString();
    }

    public static String getJSONString(int code, String msg){

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("msg", msg);
        return jsonObject.toString();
    }

    public static String getJSONString(int code, Map<String, Object> map){

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        for(Map.Entry<String, Object> m : map.entrySet()){

            jsonObject.put(m.getKey(), m.getValue());
        }
        return jsonObject.toString();
    }


    public static String MD5(String key) {
        char hexDigits[] = {
                ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘, ‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘
        };
        try {
            byte[] btInput = key.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            logger.error("生成MD5失败", e);
            return null;
        }
    }
}

 

七牛云的缩略图服务:https://developer.qiniu.com/dora/api/1279/basic-processing-images-imageview2

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

5_1_图片上传