search
HomeBackend DevelopmentPHP Tutorial七牛云如何上传图片

七牛云如何上传图片

Jun 06, 2016 pm 08:47 PM
Qiniuyunupload image

七牛云如何上传图片

七牛云上传图片的方法:

1,注册七牛云账号,

2,创建一个存储空间bucket,创建的时候回送一个临时的测试域名,这个等上传工具类要用到 ,有效期30天,

3,写java工具类

public class upLoadFile {
//...生成上传凭证,然后准备上传   这个是在注册的账户里面有个人中心那里的密钥管理
1
public static String accessKey = “h9r4Vz72dIAEL2PLSYXFEv39GmUOsw99y7wkbQQW”;
public static String secretKey = “BWhiWbB7D-lWkI2bP2c6wBYRbak3MzmcUeoyTaNv”;
// public static String bucket = “vehicle-picture”;
//这个是创建的存储空间的名字
public static String bucket = “image-a”;
//这个就是测试域名 创建的时候一般都会赠送一个测试域名
// public static String domainOfBucket = “http://qn.vwaiter.cn”;
public static String domainOfBucket = “pn7fhqast.bkt.clouddn.com”;
public static void main(String[] args)
{
getUrl(“FpMjfsJwwMDYC-IXjMIhWm9xiYt4”);
}
/**
 * 上传图片
 * @param file
 * @return
 */
public  static String  uploadFile(MultipartFile file) {
    //构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(Zone.zone0());
    //...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);
    //默认不指定key的情况下,以文件内容的hash值作为文件名
    String fileName=null;
    String key = null;
    try {
        Logger.getLogger("start>>>>>>>>>>").info("图片上传");
        byte[] uploadBytes=file.getBytes();
        ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        Response response = uploadManager.put(byteInputStream,key,upToken,null, null);
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        //key为空时默认使用hash值作为key
        System.out.println(putRet.key);
        System.out.println(putRet.hash);
        fileName=putRet.hash;
        Logger.getLogger("end>>>>>>>>>>").info("图片上传");
    }catch (QiniuException ex) {
        Response r = ex.response;
        System.err.println(r.toString());
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    return fileName;
}
/**
 * 上传图片
 * @param bytes 要上传图片的字节流
 * @return
 */
public  static String  uploadFile(byte[] bytes) {
    //构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(Zone.zone0());
    //...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);
    //默认不指定key的情况下,以文件内容的hash值作为文件名
    String fileName=null;
    String key = null;
    try {
        Logger.getLogger("start>>>>>>>>>>").info("图片上传");
        byte[] uploadBytes=bytes;
        ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        Response response = uploadManager.put(byteInputStream,key,upToken,null, null);
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        //key为空时默认使用hash值作为key
        System.out.println(putRet.key);
        System.out.println(putRet.hash);
        fileName=putRet.hash;
        Logger.getLogger("end>>>>>>>>>>").info("图片上传");
    }catch (QiniuException ex) {
        Response r = ex.response;
        System.err.println(r.toString());
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    return fileName;
}
/**
 * 字节数组上传
 * @return
 */
public static String upLoadByte(byte[] data) {
    Configuration cfg = new Configuration(Zone.zone0());
    UploadManager uploadManager = new UploadManager(cfg);
    String fileName=null;
    String key = null;
    try {
        byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(data, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            fileName=putRet.hash;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    } catch (UnsupportedEncodingException ex) {
    }
    return fileName;
}
/**
 * 生成加签访问url
 */
public  static String getUrl(String key) {
    String finalUrl=null;
    String fileName = key;
    String encodedFileName = null;
    try {
        encodedFileName = URLEncoder.encode(fileName, "utf-8");
        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        Auth auth = Auth.create(accessKey, secretKey);
        long expireInSeconds = 10800;//1小时,可以自定义链接过期时间
        finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
     } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
     }
    System.out.println(finalUrl);
    return finalUrl;
}
/**
 * 生成加签访问url
 */
public  static String getUrl1(String key) {
    String finalUrl=null;
    String fileName = key;
    String encodedFileName = null;
    try {
        encodedFileName = URLEncoder.encode(fileName, "utf-8");
        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        Auth auth = Auth.create(accessKey, secretKey);
        long expireInSeconds = 10800;//1小时,可以自定义链接过期时间
        finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
    }
    catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    System.out.println(finalUrl);
    return finalUrl;
}
//删除上传到七牛云的图片
public static boolean deleteOnQn(String key) throws Exception {
    //密钥配置
    try {
        Auth auth = Auth.create(accessKey,secretKey);
        Configuration configuration = new Configuration(Zone.autoZone());
        BucketManager bucketManager = new BucketManager(auth,configuration);
        bucketManager.delete(bucket,key);
    } catch (QiniuException e) {
        e.printStackTrace();
        throw e;
    }
    return true;
}

4,需要的依赖架

<dependency>
  <groupId>com.qiniu</groupId>
  <artifactId>qiniu-java-sdk</artifactId>
  <version>7.2.11</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
  <version>3.3.1</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.6.2</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>com.qiniu</groupId>
  <artifactId>happy-dns-java</artifactId>
  <version>0.1.4</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency>
<!--七牛云图片服务器相关依赖结束-->

5,xml里面需要文件上传处理

<!--文件上传处理器  -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>

6,写上传接口的controller和service以及serviceimpl,

更多相关技术文章,请访问PHP中文网

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment