件拖拽上傳
使用HTML5的文件API, 可以將操作系統(tǒng)中的文件拖放到瀏覽器的指定區(qū)域, 實(shí)現(xiàn)文件上傳到服務(wù)器。本文將結(jié)合實(shí)例講解HTML5+jQuery+PHP實(shí)現(xiàn)拖拽上傳圖片的過程, 來看下HTML5的魅力吧。
HTML
我們在頁面中放置一個拖拽區(qū)域#drop_area, 即接收拖拽的區(qū)域, #preview用來預(yù)覽拖拽上傳的圖片信息。
<div id="drop_area">將圖片拖拽到此區(qū)域</div>
<div id="preview"></div>
Javascript
要想實(shí)現(xiàn)拖拽, 頁面需要阻止瀏覽器默認(rèn)行為, 即四個事件(拖離、拖后放、拖進(jìn)、拖來拖去), 因?yàn)槲覀円柚篂g覽器默認(rèn)將圖片打開的行為, 這里我們使用jQuery來完成。
$(function(){
//阻止瀏覽器默認(rèn)行。
$(document).on({
dragleave:function(e){ //拖離
e.preventDefault();
},
drop:function(e){ //拖后放
e.preventDefault();
},
dragenter:function(e){ //拖進(jìn)
e.preventDefault();
},
dragover:function(e){ //拖來拖去
e.preventDefault();
}
});
...
});
接下來我們來了解下文件API。HTML5的文件API有一個FileList接口, 它可以通過e.dataTransfer.files拖拽事件傳遞的文件信息, 獲取本地文件列表信息
var fileList = e.dataTransfer.files;
在本例中, 我們用javascript來偵聽drop事件, 首先要判斷拖入的文件是否符合要求, 包括圖片類型、大小等, 然后獲取本地圖片信息, 實(shí)現(xiàn)預(yù)覽, 最后上傳。
$(function(){
/// ...接上部分
var box = document.getElementById('drop_area'); //拖拽區(qū)域
box.addEventListener("drop",function(e){
e.preventDefault(); //取消默認(rèn)瀏覽器拖拽效果
var fileList = e.dataTransfer.files; //獲取文件對象
//檢測是否是拖拽文件到頁面的操作
if(fileList.length == 0){
return false;
}
//檢測文件是不是圖片
if(fileList[0].type.indexOf('image') === -1){
alert("您拖的不是圖片!");
return false;
}
//拖拉圖片到瀏覽器,可以實(shí)現(xiàn)預(yù)覽功能
var img = window.URL.createObjectURL(fileList[0]);
var filename = fileList[0].name; //圖片名稱
var filesize = Math.floor((fileList[0].size)/1024);
if(filesize>500){
alert("上傳大小不能超過500K.");
return false;
}
var str = "<img src='"+img+"'><p>圖片名稱:"+filename+"</p><p>大小:"+filesize+"KB</p>";
$("#preview").html(str);
//上傳
xhr = new XMLHttpRequest();
xhr.open("post", "upload.php", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
var fd = new FormData();
fd.append('mypic', fileList[0]);
xhr.send(fd);
},false);
});
我們用FormData模擬表單數(shù)據(jù), 直接將數(shù)據(jù)append到formdata對象中, 實(shí)現(xiàn)了ajax上傳。
PHP
upload.php用于接收上傳的文件信息, 完成上傳, 實(shí)現(xiàn)代碼如下:
<?php
$mypic = $_FILES["mypic"];
if(!empty($mypic)){
$picname = $_FILES['mypic']['name'];
$picsize = $_FILES['mypic']['size'];
if ($picsize > 512000) {
echo '圖片大小不能超過500k';
exit;
}
$type = strstr($picname, '.');
if ($type != ".gif" && $type != ".jpg") {
echo '圖片格式不對!';
exit;
}
$pics = 'helloweba' . $type;
//上傳路徑
$pic_path = "pics/". $pics;
move_uploaded_file($mypic["tmp_name"],$pic_path);
}
?>
下邊這幾句可以沒有
<meta charset="utf-8">
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="mypic">
<input type="submit" value="上傳">
</form>
最后總結(jié)下HTML5實(shí)現(xiàn)拖拽上傳的技術(shù)要點(diǎn):
1、監(jiān)聽拖拽:監(jiān)聽頁面元素的拖拽事件, 包括:dragenter、dragover、dragleave和drop, 一定要將dragover的默認(rèn)事件取消掉, 不然無法觸發(fā)drop事件。如需拖拽頁面里的元素, 需要給其添加屬性draggable=”true”;
2、獲取拖拽文件:在drop事件觸發(fā)后通過e.dataTransfer.files獲取拖拽文件列表, .length屬性獲取文件數(shù)量, .type屬性獲取文件類型。
3、讀取圖片數(shù)據(jù)并添加預(yù)覽圖。
4、發(fā)送圖片數(shù)據(jù):使用FormData模擬表單數(shù)據(jù)AJAX提交文件流。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.max-file-size=10MB
upload.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot file upload example</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input type="submit" value="提交" />
</form>
</body>
</html>
resut.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
</body>
</html>
@Controller
public class SampleController {
@GetMapping("/")
public String upload() {
return "upload";
}
@RequestMapping("/result")
public String result() {
return "result";
}
@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:result";
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get(uploadDirectory() + "/" + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message",
file.getOriginalFilename() + " upload success");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/result";
}
private String uploadDirectory() throws FileNotFoundException {
//獲取跟目錄
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if(!path.exists()) path = new File("");
System.out.println("path:"+path.getAbsolutePath());
//如果上傳目錄為/static/images/upload/,則可以如下獲取:
File upload = new File(path.getAbsolutePath(),"static/upload/");
if(!upload.exists()) upload.mkdirs();
System.out.println("upload url:"+upload.getAbsolutePath());
//在開發(fā)測試模式時,得到的地址為:{項(xiàng)目跟目錄}/target/static/images/upload/
//在打包成jar正式發(fā)布時,得到的地址為:{發(fā)布jar包目錄}/static/images/upload/
return upload.getAbsolutePath();
}
}
選擇上傳文件進(jìn)行上傳
MinIO 是一款高性能、分布式的對象存儲系統(tǒng)。它是一款軟件產(chǎn)品, 可以100%的運(yùn)行在標(biāo)準(zhǔn)硬件上。即X86等低成本機(jī)器也能夠很好的運(yùn)行MinIO。
MinIO與傳統(tǒng)的存儲和其他的對象存儲不同的是:它一開始就針對性能要求更高的私有云標(biāo)準(zhǔn)進(jìn)行軟件架構(gòu)設(shè)計。因?yàn)镸inIO一開始就只為對象存儲而設(shè)計。所以他采用了更易用的方式進(jìn)行設(shè)計,它能實(shí)現(xiàn)對象存儲所需要的全部功能,在性能上也更加強(qiáng)勁,它不會為了更多的業(yè)務(wù)功能而妥協(xié),失去MinIO的易用性、高效性。 這樣的結(jié)果所帶來的好處是:它能夠更簡單的實(shí)現(xiàn)具有彈性伸縮能力的原生對象存儲服務(wù)。
MinIO在傳統(tǒng)對象存儲用例(例如輔助存儲,災(zāi)難恢復(fù)和歸檔)方面表現(xiàn)出色。同時,它在機(jī)器學(xué)習(xí)、大數(shù)據(jù)、私有云、混合云等方面的存儲技術(shù)上也獨(dú)樹一幟。當(dāng)然,也不排除數(shù)據(jù)分析、高性能應(yīng)用負(fù)載、原生云的支持。
在中國:阿里巴巴、騰訊、百度、中國聯(lián)通、華為、中國移動等等9000多家企業(yè)也都在使用MinIO產(chǎn)品。
使用如下命令快速安裝一個單機(jī)minio
# 下載 minio
wget https://dl.min.io/server/minio/release/linux-amd64/minio
# 添加可執(zhí)行權(quán)限
chmod +x minio
# 設(shè)置登錄minio的 access key
export MINIO_ACCESS_KEY=minioadmin
# 設(shè)置登錄minio的 secret key
export MINIO_SECRET_KEY=minioadmin
# 啟動 minio
./minio server /data
安裝后使用瀏覽器訪問http://IP地址:9000,如果可以訪問,則表示minio已經(jīng)安裝成功。輸入上面自定義的access key 和 secret key就可以登錄了。
登錄右下角加號創(chuàng)建mybucket桶
開放 mybucket 讀寫權(quán)限
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>7.0.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
編輯配置文件application.yml修改MinIO相關(guān)配置
server:
port: 8080
spring:
application:
name: minio-test
thymeleaf:
cache: false
servlet:
multipart:
max-file-size: 10MB
max-request-size: 100MB
# minio 連接參數(shù)
minio:
endpoint: 192.168.20.111
port: 9000
accessKey: minioadmin
secretKey: minioadmin
bucketName: mybucket
連接 MinIO 配置
@Data
@ConfigurationProperties(prefix = "minio")
@Component
public class MinioProp {
private String endpoint;
private String accesskey;
private String secretKey;
private int port;
}
創(chuàng)建 MinioClient
@Component
public class MinioConfiguration {
@Autowired
private MinioProp minioProp;
@Bean
public MinioClient minioClient() throws InvalidPortException, InvalidEndpointException {
//MinioClient client = new MinioClient(minioProp.getEndpoint(), minioProp.getAccesskey(), minioProp.getSecretKey());
MinioClient client = MinioClient.builder().endpoint(minioProp.getEndpoint(), minioProp.getPort(), false).credentials(minioProp.getAccesskey(), minioProp.getSecretKey()).build();
return client;
}
}
MinIO 查看桶列表,存入,刪除 操作 MinioController
@Slf4j
@RestController
public class MinioController {
@Autowired
private MinioClient minioClient;
private static final String MINIO_BUCKET = "mybucket";
@GetMapping("/list")
public List<Object> list(ModelMap map) throws Exception {
Iterable<Result<Item>> myObjects = minioClient.listObjects(MINIO_BUCKET);
Iterator<Result<Item>> iterator = myObjects.iterator();
List<Object> items = new ArrayList<>();
String format = "{'fileName':'%s','fileSize':'%s'}";
while (iterator.hasNext()) {
Item item = iterator.next().get();
items.add(JSON.parse(String.format(format, item.objectName(), formatFileSize(item.size()))));
}
return items;
}
@PostMapping("/upload")
public Res upload(@RequestParam(name = "file", required = false) MultipartFile[] file) {
Res res = new Res();
res.setCode(500);
if (file == null || file.length == 0) {
res.setMessage("上傳文件不能為空");
return res;
}
List<String> orgfileNameList = new ArrayList<>(file.length);
for (MultipartFile multipartFile : file) {
String orgfileName = multipartFile.getOriginalFilename();
orgfileNameList.add(orgfileName);
try {
InputStream in = multipartFile.getInputStream();
minioClient.putObject(MINIO_BUCKET, orgfileName, in, new PutObjectOptions(in.available(), -1));
in.close();
} catch (Exception e) {
log.error(e.getMessage());
res.setMessage("上傳失敗");
return res;
}
}
Map<String, Object> data = new HashMap<String, Object>();
data.put("bucketName", MINIO_BUCKET);
data.put("fileName", orgfileNameList);
res.setCode(200);
res.setMessage("上傳成功");
res.setData(data);
return res;
}
@RequestMapping("/download/{fileName}")
public void download(HttpServletResponse response, @PathVariable("fileName") String fileName) {
InputStream in = null;
try {
ObjectStat stat = minioClient.statObject(MINIO_BUCKET, fileName);
response.setContentType(stat.contentType());
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
in = minioClient.getObject(MINIO_BUCKET, fileName);
IOUtils.copy(in, response.getOutputStream());
} catch (Exception e) {
log.error(e.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
}
@DeleteMapping("/delete/{fileName}")
public Res delete(@PathVariable("fileName") String fileName) {
Res res = new Res();
res.setCode(200);
try {
minioClient.removeObject(MINIO_BUCKET, fileName);
} catch (Exception e) {
res.setCode(500);
log.error(e.getMessage());
}
return res;
}
private static String formatFileSize(long fileS) {
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
String wrongSize = "0B";
if (fileS == 0) {
return wrongSize;
}
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + " B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + " KB";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + " MB";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + " GB";
}
return fileSizeString;
}
}
Res返回數(shù)據(jù)封裝
@lombok.Data
@AllArgsConstructor
@NoArgsConstructor
public class Res implements Serializable {
private static final long serialVersionUID = 1L;
private Integer code;
private Object data = "";
private String message = "";
}
路由文件 RouterController
@Controller
public class RouterController {
@GetMapping({"/", "/index.html"})
public String index() {
return "index";
}
@GetMapping({"/upload.html"})
public String upload() {
return "upload";
}
}
啟動類
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.minio")
public class ServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
}
前端 列表頁面 src\main\resources\templates\index.html
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8"/>
<title>圖片列表</title>
<link rel="stylesheet" href="http://cdn.staticfile.org/element-ui/2.13.1/theme-chalk/index.css">
</head>
<body>
<div id="app">
<el-link icon="el-icon-upload" href="/upload.html">上傳圖片</el-link>
<br/>
<el-table :data="results" stripe style="width: 60%" @row-click="preview">
<el-table-column type="index" width="50"></el-table-column>
<el-table-column prop="fileName" label="文件名" width="180"></el-table-column>
<el-table-column prop="fileSize" label="文件大小"></el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<a :href="'/download/' + scope.row.fileName + ''" class="el-icon-download">下載</a>
<a :href="'/delete/' + scope.row.fileName + ''" @click.prevent="deleteFile($event,scope.$index,results)"
class="el-icon-delete">刪除</a>
</template>
</el-table-column>
</el-table>
<br/>
<el-link icon="el-icon-picture">預(yù)覽圖片</el-link>
<br/>
<div class="demo-image__preview" v-if="previewImg">
<el-image style="width: 100px; height: 100px" :src="imgSrc" :preview-src-list="imgList"></el-image>
</div>
</div>
<script src="http://cdn.staticfile.org/vue/2.6.11/vue.min.js"></script>
<script src="http://cdn.staticfile.org/axios/0.19.2/axios.min.js"></script>
<script src="http://cdn.staticfile.org/element-ui/2.13.1/index.js"></script>
<script>
new Vue({
el: '#app',
data: {
bucketURL: 'http://192.168.20.111:9000/mybucket/',
previewImg: true,
results: [],
imgSrc: '',
imgList: []
},
methods: {
init() {
axios.get('/list').then(response => {
this.results = response.data;
if (this.results.length == 0) {
this.imgSrc = '';
this.previewImg = false;
} else {
for (var i = 0; i < this.results.length; i++) {
this.imgList.push(this.bucketURL + this.results[i].fileName);
if (i == 0) {
this.imgSrc = this.bucketURL + this.results[0].fileName;
}
}
}
});
},
preview(row, event, column) {
this.imgSrc = this.bucketURL + row.fileName;
this.previewImg = true;
},
deleteFile(e,index,list) {
axios.delete(e.target.href, {}).then(res => {
if (res.data.code == 200) {
this.$message('刪除成功!');
list.splice(index, 1);
this.previewImg = false;
} else {
this.$message('刪除失敗!');
}
});
}
},
mounted() {
this.init();
}
});
</script>
</body>
</html>
前端上傳頁面 src\main\resources\templates\upload.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>圖片上傳</title>
<link rel="stylesheet" type="text/css" href="http://cdn.staticfile.org/webuploader/0.1.5/webuploader.css">
<script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.5.0/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.staticfile.org/webuploader/0.1.5/webuploader.min.js"></script>
</head>
<body>
<div id="uploader-demo">
<div id="fileList" class="uploader-list"></div>
<div id="filePicker">選擇圖片</div>
</div>
<br/>
<a href="/index.html">返回圖片列表頁面</a>
<script type="text/javascript">
var uploader = WebUploader.create({
auto: true,
swf: 'http://cdn.staticfile.org/webuploader/0.1.5/Uploader.swf',
server: '/upload',
pick: '#filePicker',
accept: {
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image/*'
}
});
uploader.on('fileQueued', function (file) {
var $li = $(
'<div id="' + file.id + '" class="file-item thumbnail">' +
'<img>' +
'<div class="info">' + file.name + '</div>' +
'</div>'
),
$img = $li.find('img');
var $list = $("#fileList");
$list.append($li);
uploader.makeThumb(file, function (error, src) {
if (error) {
$img.replaceWith('<span>不能預(yù)覽</span>');
return;
}
$img.attr('src', src);
}, 100, 100);
});
uploader.on('uploadProgress', function (file, percentage) {
var $li = $('#' + file.id),
$percent = $li.find('.progress span');
if (!$percent.length) {
$percent = $('<p class="progress"><span></span></p>')
.appendTo($li)
.find('span');
}
$percent.css('width', percentage * 100 + '%');
});
uploader.on('uploadSuccess', function (file) {
$('#' + file.id).addClass('upload-state-done');
});
uploader.on('uploadError', function (file) {
var $li = $('#' + file.id),
$error = $li.find('div.error');
if (!$error.length) {
$error = $('<div class="error"></div>').appendTo($li);
}
$error.text('上傳失敗');
});
uploader.on('uploadComplete', function (file) {
$('#' + file.id).find('.progress').remove();
});
</script>
</body>
</html>
運(yùn)行項(xiàng)目
列表頁面
參考博客:
https://blog.csdn.net/jianzhang11/article/details/105672261
*請認(rèn)真填寫需求信息,我們會在24小時內(nèi)與您取得聯(lián)系。