package cn.ellabook.server.controller.upload;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import cn.ellabook.server.controller.oss.OSSServer;
import cn.ellabook.server.dto.oss.OSSDetail;
import cn.ellabook.server.service.oss.OSSService;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
@Controller
@RequestMapping("/UploadPic")
public class UploadPicUtil {
@Resource OSSService ossService;
public static String accessKeyId = "";
public static String accessKeySecret = "";
private static String endpoint = "";
private static OSSClient ossClient = new OSSClient(endpoint,accessKeyId, accessKeySecret);
/**
* 通过路径上传oss服务器图片
* 图片上传功能 by jiangsg
* @param file
* @param memberId
* @param QRsize
* @param isDealer
* @return image path
*/
@RequestMapping(value="/test",method=RequestMethod.POST)
@ResponseBody
public Map<String, Object> uploadPIC(HttpServletRequest request,String bucket) {
bucket="ellabook-member";
Map<String, Object> map = new HashMap<String, Object>();
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;//request强制转换注意
MultipartFile file = mRequest.getFile("file");
InputStream content = null;
try {
if(!file.isEmpty()){
//设置文件的大小 4M
if(file.getSize()<1024*1024*4){
if(file.getContentType().toString().endsWith("image/jpeg")){
content = file.getInputStream();
String key = UUID.randomUUID().toString().replace("-", "")+".jpg";
ObjectMetadata meta = new ObjectMetadata();
// 必须设置ContentLength
meta.setContentLength(file.getSize());
PutObjectResult result = ossClient.putObject(bucket, key, content,meta);
System.out.println(OSSServer.ossUrl(bucket,key));
//图片上传完毕之后保存业务数据
//保存oss_bank 数据
OSSDetail ossDetail=new OSSDetail();
ossDetail.setKey(key);
ossDetail.setBucket(bucket);
ossDetail.setFilename(key);
ossDetail.setType("5_11");
int a =ossService.insertOSSSBank(ossDetail);
if(a>0){
String url = OSSServer.ossUrl(bucket,key);
map.put("url", url);
map.put("key", key);
map.put("bucket", bucket);
map.put("success", "true");
}
}else{
map.put("error", "文件格式错误,请上传图片文件!");
}
}else{
map.put("error", "图片太大,限制4M!");
}
}else{
map.put("error", "图片不存在!");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
map.put("error", "图片上传失败!");
}
return map;
}
}