java图片上传-文件/图片上传到七牛

java图片上传-文件(图片)上传到七牛


一、在配置文件中引入依赖(注:七牛开发者url:https://developer.qiniu.com/kodo)
<-- 引入依赖 -->

    com.qiniu
    qiniu-java-sdk
    7.2.6
    compile
二、工具类(UploadUtil
 
  
import java.io.IOException;
import java.io.InputStream;
import com.foriseland.fjf.base.BaseController;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
/**
* @describe 图片上传
* @author: LeoD
* @createTime 2018年3月27日 下午12:23:33
*/
public class UploadUtil extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(UploadUtil.class);
    private static final String ACCESS_KEY = "RGnPGwxZhQGoB-yEx4Yc-40位的key...";
    private static final String SECRET_KEY = "_h6eA9vScnPzhiWAdEa1-40位的key...";
    private static final String BUCKET = "test2";
    public static final String IMG_SUFFIX_LIST = "jpg,jpeg,gif,png,ico,bmp,jpeg";
    public static final String URL = "http://p22kr8qzx.bkt.clouddn.com/";
/**
* 上传图片
* @param file
* @return
* @throws IOException
*/
public static String upload(@RequestParam MultipartFile file) {
    if (file == null) {
    logger.warn("上传文件为空!");return null;
    }
    InputStream inputStream = null;
    try {
    /** 获取文件的后缀* */
        if (!checkFile(file.getOriginalFilename())) {
             logger.warn("上传文件类型不支持");
            return null;
        }
        inputStream = file.getInputStream();
        DefaultPutRet ret = qiNiuUpload(inputStream);
        if (null == ret) {
            logger.error("上传文件服务器返回为null");
            return null;
        }
        logger.info("上传图片名称:" + file.getOriginalFilename());
        logger.info("上传后hash:" + ret.hash);
        logger.info("上传后key:" + ret.key);
        return URL+"&#&"+ret.hash;
    } catch (QiniuException ex) {
        logger.error("上传七牛服务器异常", ex);
    } catch (Exception e) {
        logger.error("上传异常", e);
    } finally {
    try {
        inputStream.close();
    } catch (IOException e) {
        logger.error("上传文件,关闭输入流异常", e);
    }
   }
    return null;
}
/**
* 检测图片文件类型
* @param fileName
* @return
*/
public static boolean checkFile(String fileName) {
    boolean flag = false;
    String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
    logger.info("上传文件后缀:" + suffix);
    if (IMG_SUFFIX_LIST.contains(suffix.trim().toLowerCase())) {
        flag = true;
    }
    return flag;
}
/**
* 上传七牛服务器
* @param is
* @return
*/
private static DefaultPutRet qiNiuUpload(InputStream is) throws Exception {
    Configuration cfg = new Configuration(Zone.zone0());
    UploadManager uploadManager = new UploadManager(cfg);
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    String upToken = auth.uploadToken(BUCKET);
    com.qiniu.http.Response response = uploadManager.put(is, null, upToken, null, null);
    //解析上传成功的结果
    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
    logger.info(putRet.toString());
    logger.info(putRet.key);
    logger.info(putRet.hash);
     return putRet;
    }
}

 
  
 
  
三、入参的实体Dto
public class CrowdDto implements Serializable{
    private static final long serialVersionUID = 1L; //序列化生成uid,在后面生成一个uid
    private String crowdId; //编号
    private String userId; //用户Id
    private String crowdName;//名称
    private String crowdLogo;//群头像
    private MultipartFile multipartFile; //文件对象属性


    public MultipartFile getMultipartFile() {
         return multipartFile;
     }
     public void setMultipartFile(MultipartFile multipartFile) {
          this.multipartFile = multipartFile;
     }
     public String getCrowdName() {
      return crowdName;
     }
     public void setCrowdName(String crowdName) {
      this.crowdName = crowdName;
     }
     public String getCrowdLogo() {
      return crowdLogo;
     }
     public void setCrowdLogo(String crowdLogo) {
      this.crowdLogo = crowdLogo;
     }
     public String getUserId() {
          return userId;
     }
     public void setUserId(String userId) {
      this.userId = userId;
     }
     public String getCrowdId() {
      return crowdId;
     }
     public void setCrowdId(String crowdId) {
      this.crowdId = crowdId;
     }
    
    //生成Json字符串(类似重写ToString)
    @Override     public String toString() {
      String js = JSONObject.toJSONString(this);
      return js;
     }


    //静态生成uid
     public static long getSerialVersionUID() {
      return serialVersionUID;
     }
}
四、API层
public interface IWASCrowdInfoApi {
    /**
    * 上传文件(图片)
    * @param request* @return
    */
    public String uploadFile(@RequestBody CrowdDto requestDto);

}
五、Provide层(实现API)
/**
*
* @className: BackendCrowdInfoProvide
* @describe:
* @author: LeoD
* @createTime
*/
@Service("backendCrowdInfoProvide")
public class BackendCrowdInfoProvide implements IWASCrowdInfoApi {
    @Override
    public String uploadFile(CrowdDto requestDto) {
        return UploadUtil.upload(requestDto.getMultipartFile());
    }
}
 
   
、Controller层(通过Swagger来进行测试的,详情配置见回复的链接)




@CrossOrigin(origins = "*", maxAge = 3600)
@Controller@Api(tags="信息管理")
@RequestMapping("/crowdInfo")
public class CrowdInfoController {
private static final Logger logger = LoggerFactory.getLogger(CrowdInfoController.class);
@Autowired
private IWASCrowdInfoApi iWASCrowdInfoApi;
/*上传文件(图片)*/
@ApiOperation(value = "上传图片", notes = "上传图片", httpMethod = "POST") @RequestMapping(value="uploadFile", method=RequestMethod.POST, produces="text/plain;charset=UTF-8;", consumes="application/json") @ResponseBody
public Response uploadFile(@RequestBody CrowdDto requestDto){
String url = iWASCrowdInfoApi.uploadFile(requestDto);
Response response = Response.create();
response.setData(url);return response;
}
}








你可能感兴趣的:(JAVA)