当前位置:网站首页>Seven cattle upload pictures (foreground JS + background C API get token)
Seven cattle upload pictures (foreground JS + background C API get token)
2022-04-23 17:10:00 【Tomato Warrior】
This article is 2017 Year written , If you are trying to find seven cows JS Upload file related tutorials , Please check the latest official documents of qiniu directly I'll fill in the latest JS Upload instructions !
Try to simplify , download demo After filling in the corresponding parameters, you can directly use .
One : Get it backstage token
Things to prepare :
1、AccessKey(AK): In seven cattle - Personal panel - Key management - see ;
2、SecretKey(SK) : In seven cattle - Personal panel - Key management - see ;
3、 Destination space name (bucket); In object store - Storage space list view ;
4、 introduce Newtonsoft.Json.dll : Put it in the last download link ( problem 1: Version of the problem , The article concludes with );
5、 introduce Qiniu.dll : Put it in the last download link ;
Here is C# Complete code , All you need to fill in is 3 Parts of AK、SK、bucket
using System.Web.Http;
using Qiniu.Util;
namespace qiniutest001.Controllers
{
public class TokenController : ApiController
{
[HttpGet]
public string GetToken()
{
string AK = " Fill in your AK";
string SK = " Fill in your SK";
// Destination space name
string bucket = " Fill in the name of your target space ";
// Upload strategy
PutPolicy putPolicy = new PutPolicy();
putPolicy.Scope = bucket;
// Expiration time of upload strategy ( Company : second )
putPolicy.SetExpires(3600);
// When the file is uploaded , Automatically deleted after how many days
putPolicy.DeleteAfterDays = 1;
Mac mac = new Mac(AK, SK);
// Use AK & SK here
// Generate upload credentials
string uploadToken = Auth.createUploadToken(putPolicy, mac);
return uploadToken;
}
}
}
Two 、 Front desk request URI The address for token Upload files
Things to prepare :
1、ajax request token Of url Address ;( problem 2: Cross domain , Explain in detail at the end of the article !)
2、 Seven cattle bound domain name ( Download files using );
3、plupload.full.min.js Put it in the last download link
4、qiniu.js Put it in the last download link
5、jquery.js Put it in the last download link
The following is the full code of the page (html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/plupload.full.min.js"></script>
<script type="text/javascript" src="js/qiniu.js"></script>
<script type="text/javascript" src="js/Upimg.js"></script>
</head>
<body>
<div class="item clear" style="border-bottom: solid 1px #cccccc">
<div id="container1" style="position: relative;">
<div class="item-lee"></div>
<a class="Btn" id="pickfiles1" href="#" style="position: relative; z-index: 1;">
<i class="glyphicon glyphicon-plus"></i>
<span> Select File </span>
</a>
<!-- Displays the size of the picture -->
<div id="Size1" style="display: inline; margin-left: 20px"></div>
<!-- Reserved display information part -->
<div id="msg1" style="display: inline; margin-left: 20px"></div>
<!-- The name of the uploaded file -->
<div style="display: inline; margin-left: 20px" id="fileName1"></div>
</div>
</div>
</body>
</html>
The next step is to upload files JS part , I put it in Upimg.js in , It looks like a lot , There are only two parts to fill in url and domain
I revised the document here at seven o'clock , Put some parameters that need to be modified in the method , Pass... In the form of method parameters .
Finally, there are two ways to check the image format The method of converting units with bytes , It's not necessary to use it .
var token;// Store what we get from the background token
var url = " Fill in here ajax Request address "
var domain = " Here fill in the domain name you bind under qiniu ( There will be a default domain name )"
// The page load starts to get token, In obtaining token Of ajax in , If you get token success , Start uploading files !
$(document).ready(function () {
// obtain token
getToken();
// Initialize the upload program
//UpLoadImg(“ Select the of the file button ID”,“ Display information after uploading successfully ID”,“ After the upload is successful, the size of the file area will be displayed ID”,“ Display the name of the file after uploading the file successfully ID”)
UpLoadImg('pickfiles1', 'container1', '#msg1', '#Size1', '#fileName1');
});
// obtain token
function getToken() {
$.ajax({
type: "GET",
url: url,
async:false,
success: function(data) {
token = data;
},
error: function() {
},
beforeSend: function() {
}
});
return token;
}
//UpLoadImg(“ Select the of the file button ID”,“ Display information after uploading successfully ID”,“ After the upload is successful, the size of the file area will be displayed ID”,“ Display the name of the file after uploading the file successfully ID”)
function UpLoadImg(button,father,msg,size,fileName) {
var uploader = Qiniu.uploader({
runtimes: 'html5,flash,html4', // Upload mode , Degenerate in turn
browse_button: button, // Click the button to upload the selection ,** It's necessary **
//uptoken_url: '/token', //Ajax request upToken Of Url,** It is highly recommended to set **( Provided by the server )
uptoken: token, // If not specified uptoken_url, Must be specified uptoken ,uptoken Generated by other programs
// unique_names: true, // Default false,key For the file name . If this option is enabled ,SDK It is automatically generated after successful upload key( file name ).
// save_key: true, // Default false. If generated on the server side uptoken The upload policy of specifies `sava_key`, The open ,SDK Will ignore the right key To deal with
domain: domain, //bucket domain name , When downloading resources ,** It's necessary **
get_new_uptoken: false, // Whether to get new files every time you upload them token
container: father, // Upload area DOM ID, The default is browser_button Parent element of ,
max_file_size: '100mb', // Maximum file size limit
flash_swf_url: 'js/plupload/Moxie.swf', // introduce flash, Relative paths
max_retries: 3, // Upload failed. Maximum retries
dragdrop: true, // Enable drag upload
drop_element: 'container1', // Drag the of the upload area element ID, Dragging a file or folder triggers an upload
chunk_size: '4mb', // When uploading in blocks , The volume of each piece
auto_start: true, // Select the file and upload it automatically , If it is closed, you need to bind the event to trigger the upload
init: {
'FilesAdded': function (up, files) {
plupload.each(files, function (file) {
// After the file is added to the queue , Deal with related matters
//if (checkImg(file.name) == false)
//{
// alert(" The type of picture must be .gif,jpeg,jpg,png One of the ");
// return;
console.log(" Add queue ");
var testImgSrc = file.getNative();
});
},
'BeforeUpload': function (up, file) {
// Before each file is uploaded , Deal with related matters
console.log(" Before uploading ");
},
'UploadProgress': function (up, file) {
// When each file is uploaded , Deal with related matters
console.log(" Upload time ");
$(msg).text(' Uploading ···');
},
'FileUploaded': function (up, file, info) {
// After each file is uploaded successfully , Deal with related matters
// among info After the file is uploaded successfully , Returned by the server json, In the form of
// {
// "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
// "key": "gogopher.jpg"
// }
// Reference resources http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
var domain = up.getOption('domain');
var res = JSON.parse(info);
var sourceLink = domain + res.key; // Get the of files uploaded successfully Url
console.log(" Upload successful :" + sourceLink);
$(msg).text(' Upload successful !!');
$(size).text(bytesToSize(file.size));
$(fileName).text(' file name :' + file.name);
},
'Error': function (up, err, errTip) {
// Error uploading , Deal with related matters
console.log(" Upload error ");
alert(err);
},
'UploadComplete': function () {
// After the queue file is processed , Deal with related matters
},
'Key': function (up, file) {
// If you want to check the of each file at the front end key Personalize , This function can be configured
// The configuration must be in unique_names: false , save_key: false When it comes into effect
//var key = "";
// do something with key here
//return key
}
}
});
}
//function checkImg(url) {
//
// if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(url)) {
// return false;
// }
// else {
// return true;
// }
//}
//----------------------
// introduce Plupload 、qiniu.js after
// domain Space for seven cows (bucket) Corresponding domain name , After selecting a space , It can be done by " Space settings -> Basic settings -> Domain name settings " Check to get
// Convert size
function bytesToSize(bytes) {
if (bytes === 0) return '0 B';
var k = 1024;
sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
i = Math.floor(Math.log(bytes) / Math.log(k));
return (Math.ceil(bytes / Math.pow(k, i))) + ' ' + sizes[i];
//toPrecision(3) Leave one decimal place behind , Such as 1.0GB //return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}
So far, all the code is over .
3、 ... and 、 Demonstration mode
1、 The first is the background acquisition token, After opening the project , stay Controllers-TokenController.cs Fill in the corresponding parameters , Then start , You can view... On the web page .
2、 After starting in the background , Don't close the program , The front desk fills in the corresponding parameters , Click on ” Upload files “.
problem 1: because webAPi Brought by the project Newtonsoft.Json.dll, Need to be in webcofig Modify the version number in ;
problem 2: Because it is a local demonstration ,ajax The request will have cross domain problems , stay webconfig Add
Only need web.config Just add the following content to
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
Complete project download chain ( A little waste of you 1 integral ) Pick up :http://download.csdn.net/download/tomato2313/9763445
版权声明
本文为[Tomato Warrior]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230553458154.html
边栏推荐
- About stream flow, write it down briefly------
- Baidu Map Case - modify map style
- Nifi fast installation and file synchronization
- JS to find the character that appears three times in the string
- Generation of barcode and QR code
- ClickHouse-SQL 操作
- Getting started with JDBC
- How vscode compares the similarities and differences between two files
- JS, entries(), keys(), values(), some(), object Assign() traversal array usage
- [markdown notes]
猜你喜欢
ASP. Net core dependency injection service life cycle
Nifi fast installation and file synchronization
org. apache. parquet. schema. InvalidSchemaException: A group type can not be empty. Parquet does not su
Nacos + aspnetcore + Ocelot actual combat code
feign报400处理
Detailed explanation of the penetration of network security in the shooting range
1-4 configuration executable script of nodejs installation
RTKLIB 2.4.3源码笔记
Nodejs installation and environment configuration
Lock lock
随机推荐
Nodejs installation and environment configuration
_ Mold_ Board_
拷贝构造函数 浅拷贝与深拷贝
网络安全之渗透靶场实战详解
ASP. Net core reads the configuration file in the class library project
Getting started with JDBC
Clickhouse table engine
Paging SQL
杂文 谈谈古典的《拆掉思维里的墙》
Use between nodejs modules
Promise (IV)
Production environment——
matlab如何绘制已知公式的曲线图,Excel怎么绘制函数曲线图像?
CentOS MySQL multi instance deployment
Promise (I)
MySQL master-slave configuration under CentOS
Shell-sed命令的使用
How to implement distributed locks with redis?
[WPF binding 3] listview basic binding and data template binding
Calculation formula related to tolerance analysis