前面我们介绍了百度提供的一个富文本插件ueditor,我们还介绍了element-ui的文件上传。这一节我们将介绍一下百度提供的一个文件上传组件webuploader。
"WebUploader是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现代文件上传组件。在现代的浏览器里面能充分发挥HTML5的优势,同时又不摒弃主流IE浏览器,沿用原来的FLASH运行时,兼容IE6+,iOS 6+, android 4+。两套运行时,同样的调用方式,可供用户任意选用。采用大文件分片并发上传,极大的提高了文件上传效率。"
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
server.port=8082
spring.servlet.multipart.max-file-size=1048576000?
spring.servlet.multipart.max-request-size=1048576000?
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
@Controller
@RequestMapping("/file")
public class FileController {
/**
* 保存文件file/image
*
* @param request
* @return
*/
@RequestMapping(value = "save", method = RequestMethod.POST)
@ResponseBody
public JSONObject saveFile(HttpServletRequest request, HttpServletResponse response) {
JSONObject jsonObject = new JSONObject();
MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
MultipartFile multipartFile = req.getFile("file");
//文件上传以后在服务器的保存路径
String realPath = "D:/";
//获取上传的源文件名
String filename = multipartFile.getOriginalFilename();
//文件类型(.xxxx)
String contentType = filename.substring(filename.lastIndexOf("."));
try {
//判断文件夹是否存在
File dir = new File(realPath);
// 不存在则创建
if (!dir.exists()) {
dir.mkdirs();
}
//保存图片
File file = new File(realPath, filename);
//写出文件
multipartFile.transferTo(file);
} catch (Exception e) {
e.printStackTrace();
}
jsonObject.put("success", "true");
return jsonObject;
}
}
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class MyConfiguration {
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}
$(function () {
var baseUrl = "http://localhost:8082/file/";
/**
* 创建的WebUploadr对象
*/
var imageUploader = WebUploader.create({
// 是否开起分片上传。
chunked: false,
//选择完文件或是否自动上传
auto: false,
//swf文件路径
swf: 'Uploader.swf',
// 上传并发数。允许同时最大上传进程数[默认值:3] 即上传文件数
threads: 3,
//文件接收服务端接口
server: baseUrl + "save",
// 选择文件的按钮
pick: '#picker',
//上传请求的方法
method: "POST",
// 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
resize: false,
//指定接受哪些类型的文件
accept: {
title: 'Files',
extensions: 'gif,jpg,jpeg,bmp,png,pdf,doc,docx,txt,xls,xlsx,ppt,pptx,zip,mp3,mp4,text,csv,wmv,exe',
mimeTypes: 'image/*,text/*'
//word
+ ',application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document'
//excel
+ ',application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
//ppt
+ ',application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation'
+ ',application/pdf'
+ ',application/zip'
+ ',application/csv'
}
});
/**
* 文件被添加进队列的时候
*/
imageUploader.on('fileQueued', function (file) {
var $list = $('#filelist');
var $li = $(' <li id="' + file.id + '">' +
'<div class= "wait state">等待上传</div>' +
'<span class="delete">×</span>' +
'<img src="" alt="">' +
'<p class="filename">' + file.name + '</p>' +
'</li>'),
$img = $li.find('img');
$list.append($li);
//创建文件预览
imageUploader.makeThumb(file, function (error, src) {
if (error) {
return;
}
$img.attr('src', src);
});
});
//移除选择的文件
$('#filelist').on('click', '.delete', function () {
var fileId = $(this).parents('li').attr('id');
if (confirm("确认移除此文件吗?")) {
// 从上传队列中移除
imageUploader.removeFile(fileId, true);
// 从视图中移除缩略图
$(this).parents('li').remove();
}
});
// 文件上传过程中创建进度条实时显示。
imageUploader.on('uploadProgress', function (file, percentage) {
var $li = $('#' + file.id),
$progress = $li.find('div.progress');
// 避免重复创建
if (!$progress.length) {
$li.children('div.state').remove();
$progress = $('<div class="progress state"></div>').appendTo($li);
}
$progress.text('上传中');
});
// 文件上传成功处理。
imageUploader.on('uploadSuccess', function (file, response) {
var $li = $('#' + file.id),
$success = $li.find('div.success');
// 避免重复创建
if (!$success.length) {
$li.children('div.state').remove();
$success = $('<div class="success"></div>').appendTo($li);
}
$success.text('上传成功');
});
//上传出错
imageUploader.on('uploadError', function (file) {
var $li = $('#' + file.id),
$error = $li.find('div.error');
// 避免重复创建
if (!$error.length) {
// 移除原来的
$li.children('div.state').remove();
// 创建新的状态进度条
$error = $('<div class="error"></div>').appendTo($li);
}
$error.text('上传出错');
});
/**
* 确认上传
*/
$("#commitupload").on('click', function () {
imageUploader.upload();
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>WebUploader示例</title>
<link rel="stylesheet" href="webuploader.css">
</head>
<body>
<div id="uploader">
<div style="display: flex;justify-content: center;">
<div id="picker">选择文件</div>
<button id="commitupload">
确认上传
</button>
</div>
<ul id="filelist">
</ul>
</div>
<!-- 引入jQuery -->
<script src="jquery-1.11.2.min.js"></script>
<!-- 引入Webuploader -->
<script src="webuploader.js"></script>
<!-- 引入上传文件的js片段 -->
<script src="upload.js"></script>
</body>
</html>
启动服务端,启动浏览器端【假设端口为8080】,访问 http://localhost:8080/index.html
点击“选择文件”,选好文件,点击“确认上传”,等提示“上传成功”,则完成测试。
以上就是使用webuploader完成文件上传的过程。
原文:https://www.cnblogs.com/alichengxuyuan/p/12504501.html