Cloud storage There are many ways, here is the front-end page directly through JS upload way, should be for this way page friendly, the browser pressure is also small
Cloud storage also has many benefits:
1. Free up server disk space
2. Reduce the server disk IO pressure
3, reduce the server bandwidth pressure
4. No impact on server failure
The pits encountered:
1. Bad Uptoken
2, Error:incorrect Zone, please use up-z2.qiniu.com
3. How to get the file name
4. How to set the upload path
5. How to Get External links
6. How to get upload progress
Bad Uptoken:
In the official documentation, seven KN requires the server to return the Uptoken format to
{"Uptoken": "0mlvwpnyya1wtpnxfy9klyghyfpndzceoml ..."}
But this is very vague, tried several times to prompt bad token, eventually in uploader Uptoken should be written directly to the string format, if the server returned Uptoken please remove the double quotes at both ends, otherwise error
function Gettokenmessage () {var token;$.ajax ({url: "Http://localhost:8080/LRVideo/appservice/basic/getJSUpToken", Async:false,success:function (data) {token = data;}}) return token;} var token = gettokenmessage (); Uptoken = token.substring (Token.indexof ("\" ") +1,token.lastindexof (" \ ""));
Error:incorrect Zone, please use up-z2.qiniu.com:
Seven Bull official JS default upload area for East China, if not east of the need to modify the official JS
How to get the file name
' Key ': function (up, file) { ////If you want to personalize the Key for each file on the front-end, you can configure it //The configuration must be in Unique_names:false,save_key: False is only effective when var date = Getnowformatdate (); var fileName = file.name; Console.log ("filename" + file.name); Return key }
How to set the upload path:
function Getnowformatdate () {var mydate = new Date (); var year = Mydate.getfullyear (); var month = Mydate.getmonth () + 1;var day = Mydate.getdate (); var hour = mydate.gethours (); var min = mydate.getminutes (); VA R second = Mydate.getseconds (); if (month >= 0 && Month <= 9) {month = "0" + month; }if (Day >= 0 && Day <= 9) {day = ' 0 ' + day; }if (hour >= 0 && hour <= 9) {hour = "0" + hour; }if (min >= 0 && min <= 9) {min = "0" + min; }if (second >= 0 && second <= 9) {second = "0" + second; } var currentdate = year + "/" + month + "/" + Day + "/" + hour + "/" + min + "/" + second; return currentdate;} ' Key ': function (up, file) {////If you want to personalize the key for each file on the front end, you can configure the function//the configuration must be in Unique_names:false,save_key: False is only effective when var date = Getnowformatdate (); var fileName = File.name; var key = Getnowformatdate () + "/" + file.name; Do somEthing with key here return key}
How to Get External links:
The first thing to do here is to set up uploader domain:
Domain: ' http://onsoxm2o9.bkt.clouddn.com ',//bucket domain, download resources, required
Please refer to the external default domain name of this storage space, you can modify it yourself
' fileuploaded ': function (up, file, info) { //After each file is uploaded successfully, processing related things //where info is the JSON returned by the server after the file upload is successful, in the form of: //{ // "hash": "Fh8xvqod2mq1mocfi4s4kprl6d98", // "key": "Gogopher.jpg" // } //view Simple Feedback var domain = up.getoption (' domain '); var res = Json.parse (info); Sourcelink = domain + "/" + Res.key; Get the URL of the file after uploading successfully Console.log ("Sourcelink:" + sourcelink); },
How to get upload progress:
' Uploadprogress ': function (up, file) { var progress = new Fileprogress (file, ' fsuploadprogress '); var chunk_size = plupload.parsesize (this.getoption (' chunk_size ')); Progress.setprogress (file.percent + "%", file.speed, chunk_size); Console.log ("Progress:" + file.percent + "%"); },
The new fileprogress function is used here, which requires the introduction of the Ui.js file in the official documentation demo.
Qiniuutils
Package Com.utils.qiniu;import Java.io.ioexception;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 com.qiniu.util.stringmap;/** * Seven kn upload tool * */public Class Qiniuutils {//Set good account Access_key and secret_key String access_key = "EYBSUWG7TPXDNHZE3FEYG5DK9YZCEUNITEAUIKQH"; String Secret_key = "ICYUQBR2JM5OAOEAKEMNN_HG4IRCLDKRL0TMYGDV"; The space to upload String bucketname = "CCZB"; String bucketname2 = "Cczb-video"; Key configuration Auth Auth = Auth.create (Access_key, Secret_key); Specify the information for the zone to be uploaded////////////////////The first way: Specify the specific zone to be uploaded//NOTE: The specific way and the following automatic identification method to select one//to upload an empty (bucket) Storage area is East China//Zone z = ZONE.ZONE0 (); The storage area of the space (bucket) to be uploaded is North china/Zone Z = zone.zone1 (); The storage area of the space (bucket) to be uploaded is South China when//zone z = zone.zone2 (); The second way: automatically identify the space to upload (bucket) storage area is east, north, south China. Zone z = Zone.autozOne (); Configuration c = new configuration (z); Create an Upload object UploadManager UploadManager = new UploadManager (c); Simple upload, using the default policy, only need to set the upload space name can be public String Getuptoken () {return auth.uploadtoken (bucketname); }//js upload//scope through bucket, key indirect settings, deadline through expires indirectly set public String Getjsuptoken () {return Auth.uplo Adtoken (bucketname2); The public static void main (string[] args) {stringmap policy = new Stringmap (). Put ("Deadline", 1491159381). Put ("s Avekey "," qiangge.jpg "); Auth Auth = auth.create ("Eybsuwg7tpxdnhze3feyg5dk9yzceuniteauikqh", "ICYUQBR2JM5OAOEAKEMNN_HG4IRCLDKRL0TMYGDV"); System.err.println (Auth.uploadtoken ("Cczb-video:aaaaaaaa.jpg", "qiange2.jpg", 3600, Policy)); /** * Upload files * @author Wangqiang February 10, 2017 pm 1:09:00 * @version Brilliant v Live 2.0 * @param FilePath True path of uploaded files * @param key after uploading to seven kn saved file name (can include path), such as/test/test.png * @return */public boolean uploadfile (String FilePath, S TrinG key) {Boolean flag = false; try {//Call the Put method to upload Response res = uploadmanager.put (FilePath, Key, Getuptoken ()); Upload successful if (Res.statuscode = =) {flag = true; System.out.println ("Seven kn upload file succeeded:" + res.bodystring ()); }else{flag = false; System.out.println ("Seven Cattle upload file failed (Seven cow reason or seven cow configuration reason):" + res.bodystring ()); }} catch (Qiniuexception e) {Response r = e.response; Request failed when printing exception information System.out.println ("Seven kn upload file failed (own reason):" + r.tostring ()); Text information for try {//Response System.out.println (r.bodystring ()); } catch (Qiniuexception e1) {//ignore}} return flag; }//Upload test public void uploadtest (string FilePath, String key) throws IOException {try {//Call P Ut method upload Response res = uploadmanager.put (FilepaTh, Key, Getuptoken ()); Prints the returned information System.out.println (res.bodystring ()); System.out.println (Res.statuscode); System.out.println (Res.tostring ()); if (Res.statuscode = =) {System.out.println ("upload succeeded"); }else {System.out.println ("Upload failed:" + res.bodystring ());} } catch (Qiniuexception e) {Response r = e.response; The Information System.out.println (r.tostring ()) of the exception that was printed when the request failed; Text information for try {//Response System.out.println (r.bodystring ()); } catch (Qiniuexception e1) {//ignore}}}}
Get Uptoken
@RequestMapping (value = "/uploadfile") @ResponseBodypublic Object UploadFile (httpservletrequest request, HttpServletResponse response, @RequestParam (value = "File", Required = false) Multipartfile file) throws IOException {//To Do file Upload interface string fileName = File.getoriginalfilename (); Map<string, object> m = new hashmap<string, object> (); Bufferedoutputstream OutputStream = null;try {InputStream FileInputStream = File.getinputstream (); String Datefolder = "/" + dateutil.datetostring (new date (), "yyyy") + "/" + dateutil.datetostring (new date (), "MM") + "/" + Dateutil.datetostring (new Date (), "DD" + "/" + (Integer.parseint (dateutil.datetostring (new Date (), "HH")) +0) + Dateut Il.datetostring (new Date (), "MM" + dateutil.datetostring (new date (), "SS"));//date-named folder string Webparentpath = new File (re Quest.getsession (). Getservletcontext (). Getrealpath ("/")). GetParent (). replace ("\ \", "/");//The upper-level directory of the current Web environment string Realpath = Webparentpath + "/gcrcsuploadfile" + datefolder;//file uploaded to the server's true pathp = new File (Realpath), if (!up.exists ()) {up.mkdirs ();} String newfilename = fileName; String FilePath = "/gcrcsuploadfile" + Datefolder + "/" + Newfilename;outputstream = new Bufferedoutputstream (New FILEOUTP Utstream (New File (Realpath, NewFileName)); Ioutils.copy (FileInputStream, outputstream);//The two flows must be closed, Or the next upload to the seven bull file will be missing Fileinputstream.close (); Outputstream.close (); Logger.error ("Absolute path of file on server:" + new Files (Realpath, NewFileName). toString ()); Logger.error ("File relative path on server:" + filePath);//++++++++ upload file to seven kn +++++++++boolean flag = new Qiniuutils (). UploadFile (New File (Realpath, NewFileName). toString (). replace ("\ \", "/"), FilePath); map<string, object> data = new hashmap<string, object> ();//Save Attachment Data.put ("Picurl", FilePath);d ata.put (" Videourl ", FilePath), M.put (" status ", 0), M.put (" msg "," Upload succeeded "), M.put (" Data ", data), if (flag) {Logger.error (" ++++++++++ Upload file "+ FilePath +" to seven kn "success" ++++++++++ ");//upload to the local delete}else{m.put (" status ", 1), M.put (" msg "," Upload failed ") after uploading to the cloud successfully; M.put (" Data ", data); Logger.error ("++++++++++ upload file to seven kn" failed "++++++++++");}} catch (Exception e) {logger.error ("error on deploy process, because of file input stream", e);} finally {Outputstream.flus h (); Outputstream.close ();} return m;} /** * Seven Qiniu upload get Uptoken * @author Wanningxi * @return */@ResponseBody @requestmapping ("/getjsuptoken") public Object Getjsuptoken () {logger.error ("Get seven kn Uptoken"); map<string, object> map = new hashmap<string, object> (); try {return new Qiniuutils (). Getjsuptoken ();} catch ( Exception e) {e.printstacktrace (); Logger.error ("Exception:" + e); return Resultmaputils.systemerror (E);}}
Qiniutest.jsp
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Introduction of seven Qiniu JS upload