啥都不说 直接上代码
1.html:
<form action="/bcis/api/headImgUpload.json" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="提交"> </form>
2.contraller:
@RequestMapping(value = "/headImgUpload.json", method = RequestMethod.POST) @ResponseBody public Map<String, Object> headImgUpload(HttpServletRequest request,MultipartFile file) { Map<String, Object> value = new HashMap<String, Object>(); value.put("success", true); value.put("errorCode", 0); value.put("errorMsg", ""); try { String head = userService.updateHead(file, 4);//此处是调用上传服务接口 value.put("data", head); } catch (IOException e) { e.printStackTrace(); value.put("success", false); value.put("errorCode", 200); value.put("errorMsg", "图片上传失败"); } return value; }
3.service 此处要把
@Autowiredprivate OSSClientUtil ossClient;注进来
@Override public String updateHead(MultipartFile file, long userId) throws IOException{ String url = ImgUploadUtil.uploadImg(file, "head"); File fileOnServer = new File(url); FileInputStream fin; try { fin = new FileInputStream(fileOnServer); String[] split = url.split("/"); String s = ossClient.uploadFile2OSS(fin, split[split.length - 1]); System.out.println(s); } catch (FileNotFoundException e) { e.printStackTrace(); } userDao.updateHead(userId, url);//此处更新用户头像 return SystemConstant.IMG_URL_PREFIX + url; }
4. ImgUploadUtil帮助类
public class ImgUploadUtil { public static final String IMG_DIR = “/img/”; public static final String IMG_URL_PREFIX ="http://127.0.0.1:8080"; /** * 将图片上传到服务器 * * @param imgFile * @param type * @return */ public static String uploadImg(MultipartFile imgFile, String type) throws IOException ,ImgException{ if (imgFile.getSize() > 1024 * 1024) { throw new ImgException("上传图片大小不能超过1M!"); } SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd"); String dirPath = ImgUploadUtil.IMG_DIR + type + "/" + formater.format(new Date()); File dir = new File(dirPath); if (!dir.exists()) { dir.mkdirs(); } String fileName = ImgUploadUtil.getName(imgFile.getOriginalFilename()); if (!fileName.endsWith("png") && !fileName.endsWith("jpg") && !fileName.endsWith("gif") && !fileName.endsWith("jpeg") && !fileName.endsWith("bmp")) { throw new ImgException("上传图片请为png、jpg、gif、jpeg、bmp中的一种!"); } //原图,用于点击图片后查看原图 File fileOnServer = new File(dirPath + "/" + fileName); imgFile.transferTo(fileOnServer); return dirPath + "/" + fileName; } /** * 依据原始文件名生成新文件名 * * @return */ private static String getName(String fileName) { Random random = new Random(); return random.nextInt(10000) + System.currentTimeMillis() + ImgUploadUtil.getFileExt(fileName).toLowerCase(); } /** * 获取文件扩展名 * * @return string */ private static String getFileExt(String fileName) { return fileName.substring(fileName.lastIndexOf(".")); } }
5.上传的阿里云的帮助类OSSClientUtil
public class OSSClientUtil { Log log = LogFactory.getLog(OSSClientUtil.class); // endpoint以杭州为例,其它region请按实际情况填写 private String endpoint = "http://oss-cn-hzfinance.aliyuncs.com"; // accessKey private String accessKeyId = "您的accessKeyId "; private String accessKeySecret = "您的accessKeySecret "; //空间 private String bucketName ="您的bucketName "; //文件存储目录 private String filedir= "data/"; private OSSClient ossClient; public OSSClientUtil(){ ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); } /** * 初始化 */ public void init(){ ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); } /** * 销毁 */ public void destory(){ ossClient.shutdown(); } /** * 上传到OSS服务器 如果同名文件会覆盖服务器上的 * @param instream 文件流 * @param fileName 文件名称 包括后缀名 * @return 出错返回"" ,唯一MD5数字签名 */ public String uploadFile2OSS(InputStream instream ,String fileName){ String ret = ""; try { //创建上传Object的Metadata ObjectMetadata objectMetadata=new ObjectMetadata(); objectMetadata.setContentLength(instream .available()); objectMetadata.setCacheControl("no-cache"); objectMetadata.setHeader("Pragma", "no-cache"); objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf(".")))); objectMetadata.setContentDisposition("inline;filename=" + fileName); //上传文件 PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream , objectMetadata); ret = putResult.getETag(); } catch (IOException e) { log.error(e.getMessage(),e); }finally{ try { instream.close(); } catch (IOException e) { e.printStackTrace(); } } return ret; } /** * 从OSS获取文件 * @param filename 文件名 * @return InputStream 调用方法把流关闭 文件不存在返回null */ public InputStream downFileFromOSS(String filename){ boolean fileExist = ossClient.doesObjectExist(bucketName, filedir+ filename); if(!fileExist) return null; OSSObject ossObj = ossClient.getObject(bucketName, filedir+ filename); return ossObj.getObjectContent(); } /** * 根据文件名删除OSS服务器上的文件 * @param filename * @return */ public String deleteFile(String filename){ boolean fileExist = ossClient.doesObjectExist(bucketName, filedir+ filename); if(fileExist){ ossClient.deleteObject(bucketName, filedir+ filename); return "delok"; } else return filename+" not found"; } /** * Description: 判断OSS服务文件上传时文件的contentType * @param FilenameExtension 文件后缀 * @return String */ public static String getcontentType(String FilenameExtension){ if(FilenameExtension.equalsIgnoreCase("bmp")){return "image/bmp";} if(FilenameExtension.equalsIgnoreCase("gif")){return "image/gif";} if(FilenameExtension.equalsIgnoreCase("jpeg")|| FilenameExtension.equalsIgnoreCase("jpg")|| FilenameExtension.equalsIgnoreCase("png")){return "image/jpeg";} if(FilenameExtension.equalsIgnoreCase("html")){return "text/html";} if(FilenameExtension.equalsIgnoreCase("txt")){return "text/plain";} if(FilenameExtension.equalsIgnoreCase("vsd")){return "application/vnd.visio";} if(FilenameExtension.equalsIgnoreCase("pptx")|| FilenameExtension.equalsIgnoreCase("ppt")){return "application/vnd.ms-powerpoint";} if(FilenameExtension.equalsIgnoreCase("docx")|| FilenameExtension.equalsIgnoreCase("doc")){return "application/msword";} if(FilenameExtension.equalsIgnoreCase("xml")){return "text/xml";} return "image/jpeg"; } }
6.需要引入的jar包:gradle配置为:
compile ‘com.aliyun.oss:aliyun-sdk-oss:2.2.3‘
时间: 2024-10-10 19:19:37