File download
1. Separate the project from the front end: Export the file as a. TXT file. Console. log(res) displays the returned file content.
const handleIndividual = () = > {
/ / taskCode variables
axios.post('Requested address', {data to be passed}, {responseType: 'blob'}).then(res= > {
// Create blob objects
const blob = new Blob([res])
// Download the file name
const fileName = 'customization.txt';
// Non-IE download
// Check whether the DOWNLOAD attribute exists in the A tag
if ('download' in document.createElement('a')) {
// Create a tag
const elink = document.createElement('a')
// Assign a value to the downloaded file name
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
// Add an A tag to the body
document.body.appendChild(elink)
elink.click()
// Release the URL object
URL.revokeObjectURL(elink.href)
// Remove the A tag from the body
document.body.removeChild(elink)
} else { / / ie 10 + downloads
navigator.msSaveBlob(blob, fileName)
}
})
}
Copy the code
2. Export the front-end separately: Install it first. There are two installation methods as follows:
yarn add js-export-excel
npm install js-export-excel
Copy the code
import ExportJsonExcel from "js-export-excel";
casHoutUpload = () = > {
const { dataSource } = this.state; // Table data
let option = {};
let dataTable = [];
if (dataSource) {
for (let i in dataSource) {
if(dataSource.length ! = =0) {
// Represents the data corresponding to the table header
let obj = {
"Merchant Number": dataSource[i].mno,
'Chinese Name of Merchant': dataSource[i].mnoNm,
'English Name of Merchant': dataSource[i].mnoNmEn,
'Product Category': dataSource[i].productTypeTr,
'Product Name': dataSource[i].productName,
'Product Launch Time': dataSource[i].productOpenTime,
'Valid charges': dataSource[i].effectCount,
'Pending charges': dataSource[i].toEffectCount,
'Unaudited billing': dataSource[i].toAudEffectCount, }; dataTable.push(obj); }}}// Set the export file name
option.fileName = 'Merchant Billing Configuration - Enquiry';
option.datas = [{
sheetData: dataTable,
sheetName: 'sheet'.sheetFilter: ['Merchant No.'.'Chinese Name of Merchant'.'English Name of Merchant'.'Product Category'.'Product Name'.'Product Launch Time'.'Valid charges'.'Pending charges'.'Unaudited billing'].sheetHeader: ['Merchant No.'.'Chinese Name of Merchant'.'English Name of Merchant'.'Product Category'.'Product Name'.'Product Launch Time'.'Valid charges'.'Pending charges'.'Unaudited billing'],}];let toExcel = new ExportJsonExcel(option);
toExcel.saveExcel();
};
Copy the code
2. File upload
1. Use the Upload component of ANTD in the React framework for uploading. For details, see antD’s official website.
2. Use formData to upload files
// Create the FormData object
var formData = new FormData();
// Use the form form to get the corresponding file and other data to be passed to the back end
// Add the value that needs to be passed to the back end to the FormData object
// "dataName" is the name of the value that the back end needs to accept, and data is the value that the front end transmits
formData.append("dataName",data)
formData.append("fileName",file)
// call interface processing.Copy the code
Both this interface and formData, which provides a way to construct key-value pairs representing formData that can be sent using the xmlhttprequest.send () method, are fairly straightforward. So the formData object can do file transfer.
3. Dragging and displaying pictures
Image drag
To create an.html file, write the following code:
<div id="dropbox" style="width: 300px; height: 200px;"Drag-and-drop > < / div ><script>
// Find the corresponding element by ID
var dropbox = document.getElementById("dropbox");
// Add events
dropbox.addEventListener("dragenter", dragenter, false);
dropbox.addEventListener("dragover", dragover, false);
dropbox.addEventListener("drop", drop, false);
Emitted when the dragged element or selected text enters a valid drop target
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
Emitted when an element or selected text is dragged to a valid drop target
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
// Triggered when the mouse key is released during dragging
function drop(e) {
e.stopPropagation();
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
handleFiles(files);
}
function handleFiles(files){
// You can obtain the file information here to indicate that the drag-and-drop effect has been implemented
console.log(files)
}
</script>
Copy the code
Show drag and drop images
Override the handleFiles method:
function handleFiles(files) {
// We use a for loop here because we can drag and drop multiple images at once
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Check if it is a picture
var imageType = /^image\//;
if(! imageType.test(file.type)) {continue;
}
// Create the img tag
var img = document.createElement("img");
// Add the style name
img.classList.add("obj");
// Add the file attribute
img.file = file;
// Find elements
var preview = document.getElementById('dropbox');
// Add the created tags to preview
preview.appendChild(img);
// See the instructions below
var reader = new FileReader();
reader.onload = (function (aImg) {
return function (e) { aImg.src = e.target.result; }; })(img); reader.readAsDataURL(file); FileReader is created to handle asynchronous image loading and assign it to the IMG element. After creating a new FileReader object, we create its onload function and call readAsDataURL() to start reading the file behind the scenes. When the contents of the entire image file are fully loaded, they are converted to a data:URL that is passed to the onload callback. We then do the usual thing to set the SRC property of the IMG element to the URL just loaded so that the image can be displayed in a thumbnail on the user's screen.Copy the code
Note: The examples above do not add any styles to the added style names, you can add them if you have specific requirements
The realization effect is shown as follows:
4. Image compression upload
Image compression display
First of all, let’s take a look at whether we want such a rendering
Implementation idea: In a nutshell – Canvas drawing
- First get the file resource
- Check whether it is a picture
- Determine the size of the image and compress it if it is larger than what you want
- Read the file and convert it to an IMG tag element
- use
canvas
Compression (canvas
: is an HTML element that can be drawn using a script (usually JavaScript). - Is converted into a URL
You can see the pass in the above examplehandleFiles
Method to obtain the following file information:(Note: contrast with later)
function handleFiles(files, callback=()=>{}){
console.log(files); // 1. File resources
for (var i = 0; i < files.length; i++) {
// 2. Check whether it is a picture
// If you have strict requirements on the image format, you can make specific judgments
let file = files[i];
let imageType = /^image\//;
if(! imageType.test(file.type)) {continue;
}
// 3. This example does not limit the size of the image. Add the following code if necessary
// Determine the size of the image
// The size limit can be changed as required
// if(files[i].size /1024/1024 > 3){
// Compress the code
// }
// 4. Read the file and convert it to an IMG tag element
let reader = new FileReader();
reader.onload = ((e) = > {
const quality = 0.1; // Compress the quality
const type = "image/jpeg";
const img = document.createElement('img');
let preview = document.getElementById('dropbox');
img.src = e.target.result; // base64
img.onload = () = > {
const canvas = document.createElement('canvas'); // Create canvas
const ctx = canvas.getContext('2d');
const cvWidth = img.width * 0.5 ;
const cvHeight = img.height * 0.5 ;
// Set width and height
canvas.height = cvHeight;
canvas.width = cvWidth;
ctx.clearRect(0.0, cvWidth, cvHeight);
// Draw img onto the canvas
ctx.drawImage(img, 0.0, cvWidth, cvHeight)
// 5. Convert toDataURL to URL(base64)
leturl = canvas.toDataURL(type, quality); callback(url) } preview.appendChild(img) }) reader.readAsDataURL(file); }}/ / display
// Triggered when the mouse key is released during dragging
function drop(e) {
e.stopPropagation();
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
handleFiles(files, (url) = > {
console.log(url, 'url') // See the picture below
const img1 = document.createElement('img');
img1.src = url;
let preview = document.getElementById('dropbox');
preview.append(img1)
});
}
Copy the code
We use the toDataURL method in the handleFiles method and get the URL value as:
Image compression upload
We have already compressed and displayed the image, so for uploading we just need to change step 5 in the code comment
// 5. Convert to Blob objects using toDataURL
function handleFiles(){... canvas.toBlob(blob= > {
const file = new window.File([blob], name, { type: type });
callback(file);
},
type,
quality
);
}
function drop(e) {
e.stopPropagation();
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
handleFiles(files, (url) = > {
console.log(url, 'url') // See the picture below
// Use 2 in the file upload for this article
});
}
Copy the code
In this case, the URL obtained in the drop method is a file object, so we can get the compressed file object and call the interface to upload:
conclusion
By comparing the size in this picture with the file information before compression, we can find that the size is smaller, thus achieving the effect of compression. Images can be compressed for upload and display, just need to draw the canvas by using toBlob (file object) and toDataURL (URL base64) method conversion. In the method of compressing pictures, the image’s width and height compression ratio and quality compression ratio can be modified according to requirements.
The last
If you choose to paste the code in the article, remember to check the case, because you need to test the accuracy of writing, it may not be accurate in the case of symbols, to prevent the normal implementation of the function.
Biu biu biu ~ ❤️❤️❤️❤️ point of concern for ❤️❤️ don’t get lost