java upload pictures to the storage space of qiniu cloud

If necessary, you can join our Q group [30874228] to discuss technology and provide technical support.

We will update articles for you from time to time. Please look forward to it.

Code without saying more:

In the front end, if I am a plug-in of the layui, I need to import two files for the style:

A css style file, a js file

<script src="${ctxStatic}/layui/layui.js" charset="utf-8"></script>

html page style:

html code:

    <div class="col-xs-12">
        <div class="form-group">
            <label class="control-label col-sm-2">${text('picture')}: </label>
            <div class="col-sm-10">
                <div class="layui-upload">
                    <button type="button" class="layui-btn" id="btn_imgs"><i class="layui-icon"></i>Upload picture</button>
                    <button type="button" class="layui-btn layui-btn-normal" οnclick="resetimg()" >Empty picture</button>
                <div class="layui-upload-list">
                    <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                        <div class="layui-upload-list" id="img_imgs"></div>
                    <p id="imgsText"></p>
                    <input type="hidden" id="img" name="img" value="${zrCircle.img}">

javascript code:
//Empty picture
function resetimg(){



layui.use('upload', function(){

var $ = layui.jquery
        ,upload = layui.upload;

//How to upload multiple pictures? Just upload a single picture. Remove the two parameters multiple and number
    elem: '#btn_imgs'
    ,accept: 'images'
    ,acceptMime: 'image/*'
    ,exts: 'jpg|png|jpeg|bmp'
    ,url: '' //Change to your own upload interface
    ,multiple: true
    ,before: function(obj){
        //Pre read local file example, does not support ie8
        obj.preview(function(index, file, result){
            $('#img_imgs').append('<img src="'+ result +'" alt="'+ +'" style="margin-left:10px;" class="layui-upload-img" width="200px" height="160px">')
    ,done: function(res){
        if(res.code ==500){
            return layer.msg('Upload failed');
            //Upload succeeded
            var ss=$("#img").val();
            if (ss.length>4){
            //Click to enlarge
    ,error: function(){
        //Demonstrate failure status and implement retransmission
        var demoText = $('#imgsText');
        demoText.html('<span style="color: #Ff5722; "> upload failed < / span > < a class =" layui BTN layui BTN XS demo reload "> retry < / a > ');
        demoText.find('.demo-reload').on('click', function(){

Background java code:

 * Upload picture
 * @param file
 * @return
@PostMapping(value = "upload")
public  Map<String,Object> upload(MultipartFile file)  {
    String fileName=null;
    Map<String,Object> map=new HashMap<>();
    try {
        File f = File.createTempFile("tmp", null);
        //Transfer the file to the specified path through the transferTo(File dest) method of MultipartFile. After the MultipartFile is transferred, it can no longer be operated and an error will be reported
        fileName = QiniuCloudUtil.upload(f);
        //Delete files when the JVM process exits, usually used to delete temporary files
    } catch (IOException e) {
    return map;

QiniuCloudUtil tool class:

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.StringUtils;

import java.util.UUID;


  • @author dsn
  • @createTime 07 21:07
  • @description seven cattle cloud tool

public class QiniuCloudUtil {

// Set AK and SK of the account to be operated
private static final String ACCESS_KEY = "";
private static final String SECRET_KEY = "";
// Space name to upload
private static final String bucketname = "";
private static final String domain = "";       //External domain name
// secret key
private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

/// / upload

public static String upload(File file) throws IOException {
    // Create upload object, Zone * represents region
    Configuration configuration = new Configuration(Zone.zone2());
    UploadManager uploadManager = new UploadManager(configuration);
    try {
        // Call put method to upload
        String token = auth.uploadToken(bucketname);
        if(StringUtils.isEmpty(token)) {
            System.out.println("Not obtained token,Please try again!");
            return null;
        String imageName = UUID.randomUUID().toString();
        System.out.println("File name = "+imageName);
        Response res = uploadManager.put(file,imageName,token);
        // Print returned information
        if (res.isOK()){
            return imageName;
    }catch (QiniuException e) {
        Response r = e.response;
        // Abnormal information printed when the request fails
        System.out.println("error "+r.toString());
        try {
            // Text message for response
        } catch (QiniuException e1) {
            System.out.println("error "+e1.error());
    return null;

Note that you need to download the dependency package to use qinniu cloud:


Tags: Java Javascript JQuery jvm

Posted on Tue, 12 May 2020 10:19:01 -0400 by Kurtismonger