精华内容
下载资源
问答
  • java上传文件到oss

    2021-03-25 11:17:24
    import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; ...
    package com.aliyunoss.utils;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.InputStream;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.List;
    
    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSSClient;
    import com.aliyun.oss.OSSErrorCode;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.ServiceException;
    import com.aliyun.oss.model.CannedAccessControlList;
    import com.aliyun.oss.model.GetObjectRequest;
    import com.aliyun.oss.model.OSSObjectSummary;
    import com.aliyun.oss.model.ObjectListing;
    import com.aliyun.oss.model.ObjectMetadata;
    
    public class AliOssUtil {
    	private static final String ACCESS_ID = "";//换为自己的
    	private static final String ACCESS_KEY = "";//换为自己的
    	private static final String BUCKETNAME = "";//换为自己的
    	private static final String ENDPOINT = "";//换为自己的
    	// 创建Bucket.
        public static void ensureBucket(OSSClient client, String bucketName)
                throws OSSException, ClientException{
            try {
                // 创建bucket
                client.createBucket(bucketName);
            } catch (ServiceException e) {
                if (!OSSErrorCode.BUCKET_ALREADY_EXISTS.equals(e.getErrorCode())) {
                    // 如果Bucket已经存在,则忽略
                    throw e;
                }
            }
        }
    
        // 删除一个Bucket和其中的Objects 
        public static void deleteBucket(OSSClient client, String bucketName)
                throws OSSException, ClientException {
    
            ObjectListing ObjectListing = client.listObjects(bucketName);
            List<OSSObjectSummary> listDeletes = ObjectListing
                    .getObjectSummaries();
            for (int i = 0; i < listDeletes.size(); i++) {
                String objectName = listDeletes.get(i).getKey();
                // 如果不为空,先删除bucket下的文件
                client.deleteObject(bucketName, objectName);
            }
            client.deleteBucket(bucketName);
        }
    
        // 把Bucket设置为所有人可读
        public static void setBucketPublicReadable(OSSClient client, String bucketName)
                throws OSSException, ClientException {
            //创建bucket
            client.createBucket(bucketName);
    
            //设置bucket的访问权限,public-read-write权限
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicReadWrite);
        }
    
        /**
         * // 上传文件
         * @param client
         * @param bucketName
         * @param key
         * @param filename
         * @throws OSSException
         * @throws ClientException
         * @throws FileNotFoundException
         */
        private static void uploadFile(OSSClient client, String bucketName, String filename,String key)
                throws OSSException, ClientException, FileNotFoundException {
        	key = key.replace("\\", "/");
            File file = new File(filename);
    
            ObjectMetadata objectMeta = new ObjectMetadata();
            objectMeta.setContentLength(file.length());
    
            InputStream input = new FileInputStream(file);
            client.putObject(bucketName, key, input, objectMeta);
        }
        
        /**
         * TODO 同步到oss上
         * @param filePath文件本地路径
         * @param key oss上文件绝对路径
         */
        public static void uploadFile(String filePath,String key){
        	OSSClient client = new OSSClient(ENDPOINT, ACCESS_ID, ACCESS_KEY);
    		try {
    			String tmp = key;
    			if (key.substring(0, 1).equals("/")) {
    				tmp = key.substring(1, key.length());
    			}
    			AliOssUtil.uploadFile(client, BUCKETNAME, filePath, tmp);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
        }
        // 下载文件
        public static void downloadFile(OSSClient client, String bucketName, String key, String filename)
                throws OSSException, ClientException {
            client.getObject(new GetObjectRequest(bucketName, key),
                    new File(filename));
        }
        
        /**
        * TODO 根据文件名生成带有日期的文件相对路径
        * @param fileName
        * @return
        * @throws 
        */
        public static String getFileDatePath(String fileName) {
        	SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileStr = sf.format(new Date());
            fileName = String.format("qr-%s.png", fileName);
            String tempPath = String.join("/", fileStr.substring(0, 4), fileStr.substring(4, 6),
            		fileStr.substring(6, 8), fileStr.substring(8, 10), fileName);
            return tempPath;
        }
        
       
        
    }
    

     

    展开全文
  • java上传本地文件到oss指定目录,包含具体怎么使用,只需要改变一下配置文件就可以使用,如有疑问联系我QQ1058070168
  • java实现文件上传oss服务

    千次阅读 2019-02-27 11:42:59
    java实现文件上传oss服务 首先是pom.xml引入对应的jar包 &lt;!-- OSS文件上传 start --&gt; &lt;dependency&gt; &lt;groupId&gt;commons-httpclient&lt;/groupId&gt; &lt...

    java实现文件上传oss服务

    首先是pom.xml引入对应的jar包

    	<!-- OSS文件上传 start -->
    	<dependency>
    		<groupId>commons-httpclient</groupId>
    		<artifactId>commons-httpclient</artifactId>
    		<version>3.1</version>
    		<exclusions>
    			<exclusion>
    				<groupId>commons-codec</groupId>
    				<artifactId>commons-codec</artifactId>
    				<!--<version>1.2</version> -->
    			</exclusion>
    		</exclusions>
    	</dependency>
    	<dependency>
    		<groupId>commons-fileupload</groupId>
    		<artifactId>commons-fileupload</artifactId>
    		<version>1.3.1</version>
    	</dependency>
    	<dependency>
    		<groupId>commons-io</groupId>
    		<artifactId>commons-io</artifactId>
    		<version>2.5</version>
    	</dependency>
    	<dependency>
    		<groupId>com.alibaba</groupId>
    		<artifactId>druid</artifactId>
    		<version>1.1.6</version>
    	</dependency>
    	<!-- 支付宝授权认证 -->
    	<dependency>
    		<groupId>com.alipay.user.info.auth</groupId>
    		<artifactId>user-info-auth</artifactId>
    		<version>20161102120103</version>
    	</dependency>
    	<dependency>
    		<groupId>com.aliyun.oss</groupId>
    		<artifactId>oss</artifactId>
    		<version>2.2.1</version>
    	</dependency>
    	<dependency>
    		<groupId>commons-codec</groupId>
    		<artifactId>commons-codec</artifactId>
    		<version>1.9</version>
    	</dependency>
    	<dependency>
    		<groupId>commons-logging</groupId>
    		<artifactId>commons-logging</artifactId>
    		<version>1.2</version>
    	</dependency>
    	<dependency>
    		<groupId>org.hamcrest</groupId>
    		<artifactId>hamcrest-core</artifactId>
    		<version>1.1</version>
    	</dependency>
    	<dependency>
    		<groupId>org.jdom</groupId>
    		<artifactId>jdom</artifactId>
    		<version>1.1</version>
    	</dependency>
    	<dependency>
    		<groupId>org.apache.httpcomponents</groupId>
    		<artifactId>httpclient</artifactId>
    		<version>4.4.1</version>
    	</dependency>
    	<dependency>
    		<groupId>org.apache.httpcomponents</groupId>
    		<artifactId>httpcore</artifactId>
    		<version>4.4.1</version>
    	</dependency>
    	<!-- OSS文件上传 end -->
    

    文件上传工具类

    package com.asphalt.common.upload;
    
    import java.io.ByteArrayInputStream;
    import java.io.File;
    
    import org.slf4j.Logger;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    import com.alibaba.druid.util.StringUtils;
    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSSClient;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.GetObjectRequest;
    import com.asphalt.common.LoggerProxy;
    
    /**
     * 文件上传工具类
     * 
     * @author issuser
     * @date   2016-10-22
     */
    @Component
    public class FileUploadUtils {
    	
    	private static Logger logger=LoggerProxy.ProxyLogger(FileUploadUtils.class);
    	
    /*	private static String ossUrl = PropertiesUtil.GetValueByKey("application.properties", "asphalt.oss_url");
    	private static String bucketName = PropertiesUtil.GetValueByKey("application.properties", "asphalt.bucket_name");
    	private static String accessKeyId = PropertiesUtil.GetValueByKey("application.properties", "asphalt.access_key_id");
    	private static String accessKeySecret = PropertiesUtil.GetValueByKey("application.properties", "asphalt.access_key_secret");*/
    		
    	@Value("${asphalt.oss_url}")
    	private String ossUrl;
    	@Value("${asphalt.bucket_name}")
    	private String bucketName;
    	@Value("${asphalt.access_key_id}")
    	private String accessKeyId;
    	@Value("${asphalt.access_key_secret}")
    	private String accessKeySecret;
    	    
    
    	//Constructs a client instance with your account for accessing OSS
    	private static OSSClient client = null;
    	public OSSClient getInstance()
    	{
    		if(null == client)
    		{
    			client = new OSSClient(ossUrl, accessKeyId, accessKeySecret);
    		}
    		return client;
    	}
    	
    	/**
    	 * 文件上传
    	 * @param uploadFile
    	 * @return
    	 */
    	public boolean upload(File uploadFile) {
    		try {
    			if(uploadFile == null){
    				return false;
    			}
    			
    			getInstance().putObject(bucketName, uploadFile.getName(), uploadFile);
    			logger.info("FileUploadUtils#upload success: bucketName="+bucketName+", filename="+uploadFile.getName());
    			return true;
    		} catch (OSSException oe) {
    			logger.error("OSSException", oe);
    		} catch (ClientException ce) {
    			logger.error("ClientException", ce);
    		} 
    		return false;
    	}
    	
    	
    	/**
    	 * 文件上传
    	 * @param parentFolder 要上传的目录
    	 * @param filename	   文件名称
    	 * @param uploadFile
    	 * @return
    	 */
    	public boolean upload(String parentFolder, String filename, File uploadFile) {
    		try {
    			if(uploadFile == null || StringUtils.isEmpty(filename)){
    				return false;
    			}
    			
    			getInstance().putObject(bucketName, parentFolder + "/" +filename, uploadFile);
    			
    			logger.info("FileUploadUtils#upload success: bucketName="+bucketName+", parentFolder="+ parentFolder +", filename=" + filename);
    			
    			return true;
    		} catch (OSSException oe) {
    			logger.error("OSSException" ,oe);
    		} catch (ClientException ce) {
    			logger.error("ClientException" ,ce);
    		} 
    		return false;
    	}
    	
    	/**
    	 * 下載文件(oss文件下載)
    	 * @param file	下載文件的名字(文件名称或文件路径+名称)
    	 * @param path	下載文件的存放地址
    	 * @return
    	 */
    	public boolean download(String filename, String path){
    		boolean flag = false;
    		try{
    			getInstance().getObject(new GetObjectRequest(bucketName, filename), new File(path));
    		}catch(Exception e){
    			logger.error("FileUploadUtils#downloadFile occur error: filename="+filename+", path="+path, e);
    			return flag;
    		}
    		
    		logger.info("FileUploadUtils#downloadFile success: filename="+filename+", path="+path);
    		return true;
    	}
    	
    	
    	/**
    	 * 创建文件夹
    	 * @param folderName
    	 * @return
    	 */
    	public boolean createFolder(String folderName){
    		
    		try {
    			if(StringUtils.isEmpty(folderName)){
    				return false;
    			}
    			
    			if(!folderName.endsWith("/")){
    				folderName = folderName + "/";
    			}
    			
    			//Create an empty folder without request body, note that the key must be suffixed with a slash
    			getInstance().putObject(bucketName, folderName, new ByteArrayInputStream(new byte[0]));
    			logger.info("FileUploadUtils#createFolder success: folder name is " + folderName);
    			
    			return true;
    		} catch (OSSException oe) {
    			logger.error("OSSException" ,oe);
    		} catch (ClientException ce) {
    			logger.error("ClientException" ,ce);
    		} 
    		return false;
    	}
    	
    	
    	/**
    	 * 删除文件
    	 * 
    	 * @param filename   文件名字(全名-路径+文件名)
    	 * @return
    	 */
    	public boolean deleteFile(String filename){
    		
    		try {
    			if(StringUtils.isEmpty(filename)){
    				return false;
    			}
    			//OSSObject object = client.getObject(bucketName, filename);
    			
    			//client.deleteObject(bucketName, object.getKey());
    			getInstance().deleteObject(bucketName, filename);
    			
    			return true;
    		} catch (OSSException oe) {
    			logger.error("OSSException" ,oe);
    		} catch (ClientException ce) {
    			logger.error("ClientException" ,ce);
    		} 
    		return false;
    	}
    	
    	
    	/**
    	 * 删除文件
    	 * 
    	 * @param filename   文件夹名称
    	 * @return
    	 */
    	public boolean deleteFolder(String foldername){
    		
    		try {
    			if(StringUtils.isEmpty(foldername)){
    				return false;
    			}
    			
    			if(!foldername.endsWith("/")){
    				foldername = foldername + "/";
    			}
    			//OSSObject object = client.getObject(bucketName, filename);
    			
    			//client.deleteObject(bucketName, object.getKey());
    			getInstance().deleteObject(bucketName, foldername);
    			
    			return true;
    		} catch (OSSException oe) {
    			logger.error("OSSException" ,oe);
    		} catch (ClientException ce) {
    			logger.error("ClientException" ,ce);
    		} 
    		return false;
    	}
    
    	/**
    	 * 打印上
    	 * @param uploadId
    	 */
    	/*private static void listAllParts(String uploadId) {
    	    logger.info("Listing all parts......");
    	    ListPartsRequest listPartsRequest = new ListPartsRequest(bucketName, fileName, uploadId);
    	    PartListing partListing = client.listParts(listPartsRequest);
    	    
    	    int partCount = partListing.getParts().size();
    	    for (int i = 0; i < partCount; i++) {
    	        PartSummary partSummary = partListing.getParts().get(i);
    	        logger.info("\tPart#" + partSummary.getPartNumber() + ", ETag=" + partSummary.getETag());
    	    }
    	}*/
    }
    

    上传文件封装

    package com.asphalt.common.upload;
    
    import java.io.File;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    import javax.servlet.http.HttpServletRequest;
    import org.slf4j.Logger;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.util.FileCopyUtils;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.MultipartHttpServletRequest;
    
    import com.asphalt.common.LoggerProxy;
    import com.asphalt.common.MD5;
    
    /**
     * 上传文件到oss服务器
     * @author as
     *
     */
    @Component
    public class FileUploadOSSUtil {
    	
    	private static Logger logger=LoggerProxy.ProxyLogger(FileUploadOSSUtil.class);
    	
    	@Autowired
    	private FileUploadUtils fileUploadUtils;
    	
    	
    /*	private static final String FILE_PATH = PropertiesUtil.GetValueByKey("application.properties", "asphalt.file_path");
    	private static final String OSS_URL = PropertiesUtil.GetValueByKey("application.properties", "asphalt.oss_url");//http://oss-cn-hangzhou.aliyuncs.com
    	private static final String BUCKET_NAME = PropertiesUtil.GetValueByKey("application.properties", "asphalt.bucket_name");//oss-dev-1
    */	
    	//上传到本地服务器的路径
    	@Value("${asphalt.file_path}")
    	private String FILE_PATH;
    	@Value("${asphalt.oss_url}")
    	private String OSS_URL;
    	@Value("${asphalt.bucket_name}")
    	private String BUCKET_NAME;
    	
    	/**
    	 * 上传文件到OSS服务器
    	 * @param request
    	 * @return Map<String, Object>
    	 */
    	public Map<String, Object> uploadFileToOSS(HttpServletRequest request ,String fileFieldName) {
    		Map<String, Object> map = new HashMap<String, Object>();
    		String destPath = null;
    		try {
    			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    	        // 获取上传的文件
    	        MultipartFile file = multipartRequest.getFile(fileFieldName); 
    	        //如果上传的文件不存在
    	        if (file.isEmpty()) {
    	            map.put("success", false);
    	            map.put("msg", "上传文件不存在");
    	        } else {
    	        	//上传的原始文件名
    //	        	String origFileName = new String(file.getOriginalFilename().getBytes("ISO-8859-1"), "UTF-8");
    	        	String origFileName = file.getOriginalFilename();
    	        	//文件类型
    	        	String changeFileName = origFileName.substring(origFileName.lastIndexOf("."), origFileName.length());
    	        	//自定义文件名称
    	            String fileName = getNowDate() + "-" + System.currentTimeMillis() + changeFileName;
    	            //上传到本地服务器的路径
    	            File file1 =new File(FILE_PATH);
    	            //如果文件夹不存在,则创建    
    	            if  (!file1.exists() && !file1.isDirectory()) {       
    	                file1.mkdir();    
    	            }
    	            //上传到本地服务器的文件名称(路径+名称)
    	            destPath = FILE_PATH + fileName;
    	            //将文件上传到本地服务器路径
                	FileCopyUtils.copy(file.getBytes(), new File(destPath));
                	
    		        //文件头编码,判断文件
    		        //校验上传文件的类型,根据后缀
    		        String fileByFile = changeFileName.substring(1);
    		        boolean checkType = CheckFileType.checkType(fileByFile, uploadFileTypeList());
    		        if (checkType) {
    		        	//上传到OSS服务器的文件夹
    		        	String parentFolder = getParentFolder();
    		        	//将本地服务器的文件上传
    		        	File upFile = new File(destPath);
    		        	//上传OSS是否成功
    		        	boolean isUploadSuccess = fileUploadUtils.upload(parentFolder, fileName, upFile);
    		        	map.put("success", isUploadSuccess);
    		        	//如果上传成功,则获取上传文件地址
    		        	if(isUploadSuccess) {
    		        		String ossFileUrl = getFileOSSUrl(parentFolder ,fileName);
    		        		map.put("origFileName", origFileName);
    		        		map.put("ossFileUrl", ossFileUrl);
    		        		map.put("msg", "文件上传成功");
    		        	} else {
    		        		map.put("msg", "文件上传文件服务器失败");
    		        	}
    		        } else {
    		        	map.put("sucess", false);
    					map.put("msg", "上传文件类型不正确");
    		        }
    		        //删除本地文件
    		        deleteFile(destPath);
    	        }
    		} catch(Exception e) {
    			logger.error("文件上传oss异常",e);
    			map.put("success",false);
    			map.put("msg","文件上传失败");
    			//删除本地文件
    			deleteFile(destPath);
            }
            return map;
    	}
    	
    	/**
    	 * 上传文件到OSS服务器
    	 * @param request
    	 * @return Map<String, Object>
    	 */
    	public Map<String, Object> uploadFileToOSS2(HttpServletRequest request ,String fileFieldName) {
    		Map<String, Object> map = new HashMap<String, Object>();
    		String destPath = null;
    		try {
    			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    	        // 获取上传的文件
    	        MultipartFile file = multipartRequest.getFile(fileFieldName); 
    	        //如果上传的文件不存在
    	        if (file.isEmpty()) {
    	            map.put("success", false);
    	            map.put("msg", "上传文件不存在");
    	        } else {
    	        	//上传的原始文件名
    //	        	String origFileName = new String(file.getOriginalFilename().getBytes("ISO-8859-1"), "UTF-8");
    	        	String origFileName = file.getOriginalFilename();
    	        	long fileSize = file.getSize();
    	        	//文件类型
    	        	String changeFileName = origFileName.substring(origFileName.lastIndexOf("."), origFileName.length());
    	        	//自定义文件名称
    	            String fileName = getNowDate() + "-" + System.currentTimeMillis() + changeFileName;
    	            //上传到本地服务器的路径
    	            File file1 =new File(FILE_PATH);
    	            //如果文件夹不存在,则创建    
    	            if  (!file1 .exists() && !file1 .isDirectory()) {       
    	                file1 .mkdir();    
    	            }
    	            //上传到本地服务器的文件名称(路径+名称)
    	            destPath = FILE_PATH + fileName;
    	            //将文件上传到本地服务器路径
                	FileCopyUtils.copy(file.getBytes(), new File(destPath));
                	String fileMD5 = MD5.getMD5(new File(destPath));
                	
    		        //文件头编码,判断文件,目前只能判断,xls,xlxs,zip,rar
    		        //校验上传文件的类型,根据后缀
    		        String fileByFile = changeFileName.substring(1);
    		        boolean checkType = CheckFileType.checkType(fileByFile, uploadFileTypeList());
    		        if (checkType) {
    		        	//上传到OSS服务器的文件夹
    		        	String parentFolder = getParentFolder();
    		        	//将本地服务器的文件上传
    		        	File upFile = new File(destPath);
    		        	//上传OSS是否成功
    		        	boolean isUploadSuccess = fileUploadUtils.upload(parentFolder, fileName, upFile);
    		        	map.put("success", isUploadSuccess);
    		        	//如果上传成功,则获取上传文件地址
    		        	if(isUploadSuccess) {
    		        		String ossFileUrl = getFileOSSUrl(parentFolder ,fileName);
    		        		map.put("origFileName", origFileName);
    		        		map.put("ossFileUrl", ossFileUrl);
    		        		map.put("filePath", destPath);
    		        		map.put("fileSize", fileSize);
    		        		map.put("fileMD5", fileMD5);
    		        		map.put("msg", "文件上传成功");
    		        	} else {
    		        		map.put("msg", "文件上传文件服务器失败");
    		        	}
    		        } else {
    		        	map.put("sucess", false);
    					map.put("msg", "上传文件类型不正确");
    					//删除本地文件
    					deleteFile(destPath);
    		        }
    	        }
    		} catch(Exception e) {
    			logger.error("文件上传oss异常",e);
    			map.put("success",false);
    			map.put("msg","文件上传失败");
    			//删除本地文件
    			deleteFile(destPath);
            }
            return map;
    	}
    	
    	
    	
    	/**
    	 * 根据规则,获取OSS文件路径
    	 * @param parentFolder 父目录
    	 * @param fileName 文件名称
    	 * @return String
    	 */
    	public  String getFileOSSUrl(String parentFolder , String fileName) {
    		String prefix = "http://";
    		String webSlash = "/";
    		String genUrl = null;
    		if(OSS_URL != null) {
    			String domainName = OSS_URL.substring(7);
    			genUrl = prefix + BUCKET_NAME + "." + domainName;
    		}
    		genUrl = (genUrl == null ? OSS_URL : genUrl);
    		return genUrl + webSlash + parentFolder + webSlash + fileName;
    	}
    	
    	/**
    	 * 当前时间
    	 * @return
    	 */
    	public String getParentFolder() {
    		String ossPath = "isoftportalsweb/" + new SimpleDateFormat("yyyyMMdd").format(new Date());
    		return ossPath;
    	}
    	
    	/**
    	 * 当前时间
    	 * @return
    	 */
    	public static String getNowDate() {
    		DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
    		return df.format(new java.util.Date());
    	}
    	
    	/**
    	 * 删除本地服务器文件
    	 * @param filePath
    	 */
    	public static void deleteFile(String filePath) {
    		if (new File(filePath).exists()) {
            	new File(filePath).delete();
    		}
    	}
    	
    	/**
    	 * 允许上传文件类型列表 
    	 * @return String[] 上传文件类型列表
    	 */
    	private static String[] uploadFileTypeList() {
    		return new String[] {"JPG", "JPEG", "BMP", "PNG", "GIF" ,"XLS", "XLSX"};
    	}
    	
    }
    

    MD5类

    package com.asphalt.common;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    
    public class MD5 {
    	
    	static char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
    	
    	public static String getString(String s) throws Exception{
            char str[];
            byte strTemp[] = null;
    		try {
    			strTemp = s.getBytes("Utf-8");
    		} catch (UnsupportedEncodingException e1) {
    			e1.printStackTrace();
    		}
             if(strTemp==null) {
            	 throw new Exception("编码出错");
             }
            MessageDigest mdTemp;
            try {
                mdTemp = MessageDigest.getInstance("MD5");
                mdTemp.update(strTemp);
                byte md[]=mdTemp.digest();
                int j=md.length;
                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 (NoSuchAlgorithmException e) {
                //throw e;
            	return "";
            }
        }
    	
        /** 
         * @funcion 对文件全文生成MD5摘要  
         * @param file:要加密的文件 
         * @return MD5摘要码 
         */  
        public static String getMD5(File file) {  
            FileInputStream fis = null;  
            try {  
                MessageDigest md = MessageDigest.getInstance("MD5");  
                fis = new FileInputStream(file);  
                byte[] buffer = new byte[2048];  
                int length = -1;  
                while ((length = fis.read(buffer)) != -1) {  
                    md.update(buffer, 0, length);  
                }  
                byte[] b = md.digest();  
                return byteToHexString(b);  
            } catch (Exception e) {  
                e.printStackTrace();  
                return null;  
            } finally {  
                try {  
                    fis.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }   
      
        /** 
         * @function 把byte[]数组转换成十六进制字符串表示形式 
         * @param tmp  要转换的byte[] 
         * @return 十六进制字符串表示形式 
         */  
        private static String byteToHexString(byte[] tmp) {  
            String s;  
            // 用字节表示就是 16 个字节  
            // 每个字节用 16 进制表示的话,使用两个字符,所以表示成 16 进制需要 32 个字符  
            // 比如一个字节为01011011,用十六进制字符来表示就是“5b”  
            char str[] = new char[16 * 2];  
            int k = 0; // 表示转换结果中对应的字符位置  
            for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5 的每一个字节转换成 16 进制字符的转换  
                byte byte0 = tmp[i]; // 取第 i 个字节  
                str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换, >>> 为逻辑右移,将符号位一起右移  
                str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换  
            }  
            s = new String(str); // 换后的结果转换为字符串  
            return s;  
        }  
      
    //    public static void main(String arg[]) throws Exception {  
    //    	String A = getString("12345asfkfk");
    //    	System.out.println(A);
    //    	long l1 = System.currentTimeMillis();
    //        String a = getMD5(new File("E:/data/内乡/贫困/贫困户信用信息(全).rar"));  
    //        long l2 = System.currentTimeMillis();
    //        System.out.println(l2-l1);
    //        String b = getMD5(new File("e:/2.txt"));  
    //        System.out.println("1.txt的摘要值为:" + a);  
    //        System.out.println("2.txt的摘要值为:" + b);  
    //        if(a.equals(b)) {  
    //            System.out.println("a.txt中的内容与b.txt中的内容一致");  
    //        } else {  
    //            System.out.println("a.txt中的内容与b.txt中的内容不一致");  
    //        }  
    //    }
        
    }
    
    展开全文
  • 主要介绍了java实现上传文件到oss(阿里云)功能,结合实例形式详细分析了java上传文件到阿里云的具体步骤、配置及相关实现技巧,需要的朋友可以参考下
  • 需要的依赖 <dependency> <groupId>com.aliyun.oss</groupId> ...aliyun-sdk-oss</artifactId> <version>2.4.0</version> </dependency> <depe...

    需要的依赖

    <dependency>
        <groupId>com.aliyun.oss</groupId>
        <artifactId>aliyun-sdk-oss</artifactId>
        <version>2.4.0</version>
    </dependency>
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
    </dependency>
    <dependency>
        <groupId>org.jdom</groupId>
        <artifactId>jdom</artifactId>
        <version>1.1.3</version>
    </dependency>
    

    配置文件

    #OSS
    java4all.file.endpoint=oss-cn-beijing.aliyuncs.com
    java4all.file.keyid=xxx
    java4all.file.keysecret=xxx
    #这个自己创建bucket时的命名,控制台创建也行,代码创建也行
    java4all.file.bucketname=xxx
    #文件路径,我这里是hyxy
    java4all.file.filehost=xxx
    

    在这里插入图片描述

    用到的两个工具类

    @Component
    public class ConstantProperties implements InitializingBean {
    
    	    @Value("${java4all.file.endpoint}")
    	    private String java4all_file_endpoint;
    	
    	    @Value("${java4all.file.keyid}")
    	    private String java4all_file_keyid;
    	
    	    @Value("${java4all.file.keysecret}")
    	    private String java4all_file_keysecret;
    	
    	    @Value("${java4all.file.filehost}")
    	    private String java4all_file_filehost;
    	
    	    @Value("${java4all.file.bucketname}")
    	    private String java4all_file_bucketname;
    	
    	
    	    public static String JAVA4ALL_END_POINT         ;
    	    public static String JAVA4ALL_ACCESS_KEY_ID     ;
    	    public static String JAVA4ALL_ACCESS_KEY_SECRET ;
    	    public static String JAVA4ALL_BUCKET_NAME1      ;
    	    public static String JAVA4ALL_FILE_HOST         ;
    	
    	    @Override
    	    public void afterPropertiesSet() throws Exception {
    	        JAVA4ALL_END_POINT = java4all_file_endpoint;
    	        JAVA4ALL_ACCESS_KEY_ID = java4all_file_keyid;
    	        JAVA4ALL_ACCESS_KEY_SECRET = java4all_file_keysecret;
    	        JAVA4ALL_FILE_HOST = java4all_file_filehost;
    	        JAVA4ALL_BUCKET_NAME = java4all_file_bucketname;
    	    }
    
    }
    
    
    
    
    
    
    
    public class AliyunOSSUtil {
        public static String endpoint=ConstantProperties.JAVA4ALL_END_POINT;
        public static String accessKeyId=ConstantProperties.JAVA4ALL_ACCESS_KEY_ID;
        public static String accessKeySecret=ConstantProperties.JAVA4ALL_ACCESS_KEY_SECRET;
        public static String bucketName=ConstantProperties.JAVA4ALL_BUCKET_NAME;
        //public static String fileHost=ConstantProperties.JAVA4ALL_FILE_HOST;
        //打印日志
        private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);
    
    	//fileHost为文件路径
    	//a只是业务需要 可以去掉
    	//上传文件到OSS
        public static String upload(File file,String fileHost,Integer a){
            logger.info("=========>OSS文件上传开始:"+file.getName());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = format.format(new Date());
            if(null == file){
                return null;
            }
    
            OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
            try {
                //容器不存在,就创建
                if(! ossClient.doesBucketExist(bucketName)){
                    ossClient.createBucket(bucketName);
                    CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                    createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                    ossClient.createBucket(createBucketRequest);
                }
                //创建文件路径
                String fileUrl= null;
                if(a == 1){
                     fileUrl = fileHost;
                }else{
                     fileUrl = fileHost+"/"+(dateStr + "/" + UUID.randomUUID().toString().replace("-","")+file.getName());
                }
    
                //上传文件
                PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
                //设置权限 这里是公开读
                ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
                if(null != result){
                    logger.info("==========>OSS文件上传成功,OSS地址:"+fileUrl);
                    return fileUrl;
                }
            }catch (OSSException oe){
                logger.error(oe.getMessage());
            }catch (ClientException ce){
                logger.error(ce.getMessage());
            }finally {
                //关闭
                ossClient.shutdown();
            }
            return null;
        }
    
        /*判断OSS中文件是否存在*/
        public static boolean verifyExist(String filePath){
            OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
            return ossClient.doesObjectExist(bucketName, filePath);
        }
    
    	//删除OSS文件
        public static String deleteBlog(String fileKey){
            logger.info("=========>OSS文件删除开始");
            try {
                OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
    
                if(!ossClient.doesBucketExist(bucketName)){
                    logger.info("==============>您的Bucket不存在");
                    return "您的Bucket不存在";
                }else {
                    logger.info("==============>开始删除Object");
                    ossClient.deleteObject(bucketName,fileKey);
                    logger.info("==============>Object删除成功:"+fileKey);
                    return "==============>Object删除成功:"+fileKey;
                }
            }catch (Exception ex){
                logger.info("删除Object失败",ex);
                return "删除Object失败";
            }
        }
    }
    

    更多方法查看link.(点击link就可以跳转到下图页面,或者复制https://help.aliyun.com/document_detail/32074.html?spm=a2c4g.11186631.6.753.bCnZnU#h2-u5220u9664u6587u4EF6)

    ?

    展开全文
  • 一,实现文件上传(图片,文件,音视频) 普通的上传 @Override public Object uploadImage(MultipartFile file) { //获取文件名 String originalFilename = file.getOriginalFilename(); //获取文件后缀名 ...
    一,实现文件上传(图片,文件,音视频)

    普通的上传

    @Override
    public Object uploadImage(MultipartFile file) {
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀名
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        System.out.println(substring);
        //使用时间戳改变文件名
        String fileName = System.currentTimeMillis()+"."+substring;
        String filePath = "E:\\data\\";
        String fileUrl = filePath+fileName;
        File dest = new File(fileUrl);
        //判断是否存在此目录,不存在则创建此目录
        if (!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        }catch (Exception e){
            e.printStackTrace();
            return CommonResult.failed(originalFilename+"上传失败!");
        }
        return CommonResult.success("上传成功!  "+fileUrl);
    }
    

    二,文件上传到OSS服务器

    需要引入的依赖

    <!--OSS-->
            <dependency>
                <groupId>com.aliyun.oss</groupId>
                <artifactId>aliyun-sdk-oss</artifactId>
                <version>2.4.0</version>
            </dependency>
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.1</version>
            </dependency>
            <dependency>
                <groupId>org.jdom</groupId>
                <artifactId>jdom</artifactId>
                <version>1.1.3</version>
            </dependency>
    

    具体的代码,不包含业务逻辑

     @Override
        public Object uploadImageOss(MultipartFile file) throws Exception {
            // Endpoint以北京为例,其它Region请按实际情况填写。
            String endpoint = "http://oss-cn-beijing.aliyuncs.com";
            // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
            String accessKeyId = "xxxxxxxx";
            String accessKeySecret = "xxxxxxx";
            //创建的bucket名
            String bucketName = "xxxxxx";
    		//获取文件名
            String originalFilename = file.getOriginalFilename();
            //获取文件后缀名
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //使用uuid作为文件名防止重复
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String fileName = uuid+"."+substring;
            final File tempFile = File.createTempFile(uuid, substring);
            //MultipartFile  转换为 File
            file.transferTo(tempFile);
            // 创建OSSClient实例。
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            try {
                //容器不存在,就创建
                if(! ossClient.doesBucketExist(bucketName)){
                    ossClient.createBucket(bucketName);
                    CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                    createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                    ossClient.createBucket(createBucketRequest);
                }
                String fileHost = "upload";
                //上传文件
                //File file1 = multipartFileToFile(file);
                //创建文件路径
                String fileUrl= fileHost+"/"+fileName;
                PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, tempFile));
                //设置权限 这里是公开读
                ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
                if(null != result){
                    log.info("==========>OSS文件上传成功,OSS地址:"+fileUrl);
                    return CommonResult.success(fileUrl);
                }
            }catch (OSSException oe){
                log.error(oe.getMessage());
            }catch (ClientException ce){
                log.error(ce.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //关闭
                ossClient.shutdown();
            }
            //删除临时生成的文件
            deleteFile(tempFile);
            return null;
        }
    
        /**
         * 删除
         *
         * @param files
         */
        private void deleteFile(File... files) {
            for (File file : files) {
                if (file.exists()) {
                    file.delete();
                }
            }
        }
    
    展开全文
  • java 上传文件到oss(阿里云)

    千次阅读 2017-04-28 10:27:07
    aliyun-sdk-oss-2.5.0.jar 这个文件 如果有最新版的话就下载最新版aliyun.upload.AliyunConfigpackage aliyun.upload;public final class AliyunConfig { //你的oss所在域,要加http:// 不明白可以对照你的文件...
  • JAVA本地上传文件到OSS服务器

    千次阅读 2019-11-26 18:07:57
    最近需要把文件上传到阿里云服务器,简单记录一下,看了很多文章都没有标出来使用的jar包,首先maven项目在pom文件里添加 <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>...
  • java上传文件夹到oss

    2019-09-05 16:21:28
    前段时间正好做个项目,就是用的oss,普通上传和断点续,代码贴出来,看是不是你们需要的 public class OssManage { public static String ACCESS_KEY_ID = null; public static String ACCESS_KEY_SECRET = ...
  • 为啥写这篇博客,按理说这个很简单,但我在找资料的时候,没有找到好的资料,之前还走了一些弯路,所以记下,希望能帮助看到的臭弟弟!! 三部曲 引依赖 compile 'com.aliyun.oss:aliyun-sdk-oss:3.6.0' maven的...
  • 文章目录1、创建Bucket2、获取AccessKey3、找开发文档4、后端集成OSS1、创建子模块service-oss并配置pom.xml2、配置application.properties3、启动项目4、从配置文件读取信息5、编写上传代码6、使用swagger测试接口7...
  • h5上传文件到阿里云OSS: 处理逻辑: 第一步:前端点击上传文件按钮 第二步:调服务器接口获取到上传oss相关参数的签名参数值 第三步:前端直接接收返回的参数进行表单方式上传文件 服务器controller代码:...
  • 主要介绍了微信小程序环境下将文件上传到OSS的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
  • 使用阿里云OSS上传文件 本文介绍如何利用Java API操作阿里云OSS对象存储。 1.控制台操作 首先介绍一下阿里云OSS对象存储的一些基本概念。 1.1 进入对象存储界面 登录阿里云账号,进入对象存储界面(点击跳转)...
  • java 文件上传和下载 oss

    千次阅读 2019-07-08 17:57:39
    话不多说 直接粘代码 先从 阿里云上下载下来对应的java的sdk ... 简单的文件上传和下载 @Slf4j public class UploadFile { @Value("${aliyun.e...
  • -- 阿里云oss依赖 --> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.8.1</version> </dependency>...
  • Java上传图片到OSS

    2017-07-18 13:31:11
    上传主方法 package cn.osworks.aos.huijia.modules.utils; ...import java.io.File;...import java.io.FileInputStream;...import java.io.FileNotFoundException;...import java.io.InputStream;...import java.util
  • 主要为大家详细介绍了java获取网络图片上传到OSS,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
  • 阿里云OSS Java SDK 首先想使用阿里云OSS服务先要去官网申请:阿里云API的密钥AccessKeyID、阿里云API的密钥AccessKeySecret 有了这两个才能进行开发。 阿里云官方有针对不同语言设计的SDK包,本文使用java SDK。...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 11,092
精华内容 4,436
关键字:

java文件上传到oss

java 订阅