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>
                    </blockquote>
                    <p id="imgsText"></p>
                    <input type="hidden" id="img" name="img" value="${zrCircle.img}">
                </div>
                </div>
            </div>
        </div>
    </div>
</div>

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

$('#img_imgs').empty();
$("#img").val("");

}

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
upload.render({
    elem: '#btn_imgs'
    ,accept: 'images'
    ,acceptMime: 'image/*'
    ,exts: 'jpg|png|jpeg|bmp'
    ,url: '' //Change to your own upload interface
    ,multiple: true
    ,number:5
    ,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="'+ file.name +'" style="margin-left:10px;" class="layui-upload-img" width="200px" height="160px">')
        });
    }
    ,done: function(res){
        if(res.code ==500){
            return layer.msg('Upload failed');
        }else{
            //Upload succeeded
            var ss=$("#img").val();
            if (ss.length>4){
                ss=ss+","+res.url;
            }else{
                ss=res.url;
            }
            $("#img").val(ss);
            //Click to enlarge
            renderImg();
        }
    }
    ,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(){
            uploadInst.upload();
        });
    }
});

});
Background java code:
/**

 * Upload picture
 * @param file
 * @return
 */
@PostMapping(value = "upload")
@ResponseBody
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
        file.transferTo(f);
        fileName = QiniuCloudUtil.upload(f);
        fileName="http://qiniu.zenran.com/"+fileName;
        System.out.println(fileName);
        //Delete files when the JVM process exits, usually used to delete temporary files
        f.deleteOnExit();
        map.put("code",200);
        map.put("url",fileName);
    } catch (IOException e) {
        map.put("code",500);
        map.put("url",fileName);
        e.printStackTrace();
    }
    return map;
}

QiniuCloudUtil tool class:

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

import java.io.File;
import java.io.IOException;
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
        e.printStackTrace();
        System.out.println("error "+r.toString());
        try {
            // Text message for response
            System.out.println(r.bodyString());
        } catch (QiniuException e1) {
            System.out.println("error "+e1.error());
        }
    }
    return null;
}

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

        <groupId>com.qiniu</groupId>
        <artifactId>qiniu-java-sdk</artifactId>
        <version>7.2.28</version>
    </dependency>

Tags: Java Javascript JQuery jvm

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