IView file upload (DIRECT OSS)
Preface:
A third-party open source UI framework called View UI (iView) was used in the early project. The overall feel of the UI framework is pretty good. But now that the View UI is commercialized, you have to pay for some of the functionality. Recently, the function module needs to Upload files, so I thought of the Upload module in UI, and decided to use it to Upload files. The UI’s own file upload is chosen mainly because of its configurability and upload progress bar. This file Upload involves large file Upload, so the waiting time is a little long. In order to display the Upload progress in real time, the Upload is adopted, which has a configurable Upload progress bar and a list of uploaded files, just meeting my needs.
Requirements:
This file upload requires direct transfer (OSS) to Ali Cloud server. However, there is no configuration related to THE UPLOAD of OSS files in the official example. In order to achieve the purpose of direct transmission of OSS, we now use the existing case Demo to further rewrite and realize the upload of files to Ali Cloud server.
<Form ref="voteForm" :model="voteForm" :label-width="120">
<FormItem label="Upload attachments">
<! -- Attachment link address -->
<input type="hidden" v-model.trim="voteForm.filePath" />
<! -- Upload -->
<Upload
:disabled="loading"
:action="upAction"
:data="upData"
:format="upFormat"
:before-upload="beforeUpload"
:on-success="onSuccess"
:on-error="onError"
:on-remove="onRemove"
:on-format-error="onFormatError"
:default-file-list="defaultFile"
>
<Button type="primary" icon="ios-cloud-upload-outline" :loading="loading">{{ loading ? "On..." : "Upload attachment"}}</Button>
</Upload>
<! -- Prompt text -->
<p style="color:red;">Tips: Please upload the specified file format of the file!</p>
</FormItem>
</Form>
Copy the code
Parameter configuration details:
attribute | instructions | type | The default value |
---|---|---|---|
action | Upload address, mandatory | String | – |
disabled | Whether to disable | Boolean | false |
data | Additional parameters attached to upload | Object | – |
name | Name of the file field to be uploaded | String | file |
show-upload-list | Whether to display the list of uploaded files | Boolean | true |
type | Type of the upload control. The optional value isselect (Click Select),drag (Support drag and drop) |
String | select |
accept | UploadableThe file type | String | – |
format | Supported file types. Different from Accept, format is the suffix used to identify files. Accept is the native Accept attribute of the input tag | Array | [] |
before-upload | The hook before uploading the file, which takes the uploaded file and stops uploading if false or Promise is returned | Function | – |
on-success | Hook for uploading a file successfully. The return fields are Response, file, fileList | Function | – |
on-error | Hook for file upload failure. Return fields are error, file, fileList | Function | – |
on-remove | File list Hook for removing a file. Return fields are file, fileList | Function | – |
on-format-error | Hook for failed file format validation. Return fields are file, fileList | Function | – |
on-exceeded-size | Hook for files that exceed the specified size limit. Return fields are file, fileList | Function | – |
default-file-list | Default list of uploaded files, for example:[{name: '',url: ''}] |
Array | [] |
[oss. Js] file:
const oss = {
accessKeyId: "" /* User requested accessid */ ,
accessKeySecret: "" / * * / ,
signature: "" /* Upload file signature information */ ,
policy: "" /* User form upload policy */ ,
path: "https://xxxxxx.oss-cn-beijing.aliyuncs.com" /* Upload aliyun server address */ ,
filePath: "oss_file/" /* OSS upload file path (generate the specified folder) */
};
/* Rename the file */
const fileRename = fileName= > {
let suffixName = fileName;
if (fileName.lastIndexOf(".") != -1) {
suffixName = fileName.substring(fileName.lastIndexOf("."));
}
const moment = new Date(a);let yyyy = moment.getFullYear(),
MM = moment.getMonth() + 1,
dd = moment.getDate(),
hh = moment.getHours(),
mm = moment.getMinutes(),
ss = moment.getSeconds();
MM = MM <= 9 ? "0" + MM : MM;
dd = dd <= 9 ? "0" + dd : dd;
let rm = (Math.random() * 1e5).toFixed(),
path = `${yyyy}${MM}/${dd}_${hh}${mm}${ss}_${rm}`;
return path + suffixName;
};
export { oss, fileRename };
Copy the code
Note: Present globally common properties and methods.
Upload file property configuration:
import { oss, fileRename } from ".. /utils/oss";
export default {
name: "Upload".data() {
return {
loading: false.defaultFile: [] /* { name: "", url: "" } */ ,
upAction: oss.path /* Upload path */ ,
upData: {
key: "" /* File path/file name */ ,
policy: "".OSSAccessKeyId: "".success_action_status: 200 /* Status code */ ,
signature: "".name: "" /* File name */
} /* Upload parameters */ ,
upFormat: ["jpg"."jpeg"."png"] /* Upload file type */ ,
voteForm: {} /* Form form */}; },methods: {
// Before uploading the file
beforeUpload(file) {
/* Rename the file */
let fileName = fileRename(String(file.name));
// Pass parameters
let {
accessKeyId,
policy,
signature,
filePath
} = oss;
Object.assign(this.upData, {
key: filePath[0] + fileName,
policy: policy,
OSSAccessKeyId: accessKeyId,
signature: signature,
name: fileName
});
this.loading = true;
},
// Upload success callback
onSuccess(response, file, fileList) {
this.loading = false; ! [](https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/d8a13c44e8c94c52a2c6b57af3f19a27~tplv-k3u1fbpfcp-watermark.image)
// Concatenate the complete address
let fileURI = this.upAction + "/" + this.upData.key;
this.voteForm.filePath = fileURI;
console.log("Generate file address:", fileURI);
this.$Message.success({
background: true.content: "File uploaded successfully"
});
},
// Remove the file
onRemove(file) {
this.voteForm.filePath = "";
this.$Message.success({
background: true.content: "Attachment removed successfully"
});
},
// Failed to upload file
onError(error, file) {
this.loading = false;
this.$Message.error({
background: true.content: "File upload failed, please try again later!"
});
},
// Failed to upload file format
onFormatError(file) {
// The uploaded file format does not match the specified file format
this.loading = false;
this.$Message.error({
background: true.content: "Upload file format error, please select a new file type!"}); }}};Copy the code
Matters needing attention:
- Single file upload is used in this project. If you need to configure multiple files, please refer to API on the official website.
- Dynamic concatenation of upload parameters requires assigning default values to properties in advance, which is intercepted in the beforeUpload hook function.
- Before uploading the file, obtain other parameters of OSS direct transmission and assign values. Otherwise, the uploaded file parameter will display a default value file.
- In the beforeUpload function, returns false or Promise will stop the file upload;
- In direct transmission of OSS, the return value of response in the onSuccess callback function may be empty. In this case, you need to manually combine the absolute address of the uploaded file to assign the value.