使用Dropzone上传图片及回显演示样例
一、图片上传所涉及到的问题
1、HTML页面中引入这么一段代码
<div class="row">
<div class="col-md-12">
<form dropzone2 class="dropzone" enctype="multipart/form-data" method="post"></form>
</div>
</div>
2、 在指令中发送POST请求
关键代码例如以下
var manage = angular.module('hubBrowseManageDirectives', []);
manage.directive('dropzone2', function () {
return {
restrict: 'EA',
controller: ['$scope', '$element', '$attrs', '$timeout', function ($scope, $element, $attrs, $timeout) {
$element.dropzone({
url : "rest/components/"+$scope.component.name+"/"+$scope.component.version+"/images",
autoDiscover : false,
autoProcessQueue: true,
addRemoveLinks: true,
addViewLinks: true,
acceptedFiles: ".jpg,.png",
dictDefaultMessage: "upload head picture",
maxFiles : "1",
dictMaxFilesExceeded: "Only can upload one picture, repeat upload will be deleted!",
init: function () {
var mockFile = { name: "Filename",
size: 10000
};
this.emit("addedfile", mockFile);
mockFile._viewLink.href = "rest/components/"+$scope.component.name+"/"+$scope.component.version +"/"+$scope.component.image;
mockFile._viewLink.name = $scope.component.image;
this.emit("thumbnail", mockFile, "rest/components/"+$scope.component.name+"/"+$scope.component.version +"/"+$scope.component.image);
this.emit("complete", mockFile);
$(".dz-view").colorbox({
rel:'dz-view',
width:"70%",
height:"80%"
});
this.on("error", function (file, message) {
alert(message);
this.removeFile(file);
});
this.on("success", function(file,imageInfo) {
file._viewLink.href = imageInfo.newfile;
file._viewLink.name = imageInfo.newfile;
$scope.$apply(function() {
$scope.component.image="rest/components/"+$scope.component.name+"/"+$scope.component.version+"/"+imageInfo.newfile;
});
});
this.on("removedfile", function(file) {
var removeFileUrl = file._viewLink.name;
if($scope.component.image == removeFileUrl){
this.removeFile(file);
}
});
}
});
}]
};
});
注意上述URL的请求方式,要在Angular模拟请求中放行。
格式例如以下:
var hubMock = angular.module('hubMock', ['ngMockE2E']);
hubMock.run(['$httpBackend', '$http', function ($httpBackend, $http) {
$httpBackend.whenGET(/\.html/).passThrough();
$httpBackend.whenGET(/\.json/).passThrough();
$httpBackend.whenPOST(/rest\/components\/.+\/.+\/images/).passThrough();
}]);
$httpBackend.whenPOST(/rest\/components\/.+\/.+\/images/).passThrough(); 放行图片上传发送是POST 请求。
3、处理上传图片的请求将其存储在本地
@POST
@Path("/{componentName: \\w+}/{version: \\d\\.\\d\\.\\d}/images")
@Produces(MediaType.APPLICATION_JSON)
public Response uploadMyComponentImage(@Context HttpServletRequest request, @PathParam("componentName") String componentName,
@PathParam("version") String version) {
Map<String, String> infoMap = componentService.uploadMyComponentImage(request, componentName, version);
return Response.ok(infoMap).build();
}
4、通过接口及事实上现类来处理图片上传的位置
@Override
public Map<String, String> uploadMyComponentImage(HttpServletRequest request, String componentName, String version) {
Map<String, String> infoMap = new HashMap<String, String>();
String url = null;
try {
url = application.getStorageLocation(File.separator + componentName + File.separator + version).getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
Map<String, List<FileItem>> items = upload.parseParameterMap(request);
for (Entry<String, List<FileItem>> entry : items.entrySet()) {
String key = entry.getKey();
Iterator<FileItem> itr = items.get(key).iterator();
while (itr.hasNext()) {
FileItem item = itr.next();
String newfileName = UUID.randomUUID().toString() + "-" + item.getName();
infoMap.put("newfile", "" + newfileName);
File file = new File(url);
if (!file.exists()) {
file.mkdirs();
}
file = new File(url + File.separator + "img" + File.separator + newfileName);
item.write(file);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return infoMap;
}
在这里返回的是一个map, key是newfile,value是”” + newfileName,因此在上传成功后就能够取得图片的信息。例如以下演示样例 imageInfo.newfile;:
this.on("success", function(file,imageInfo) {
file._viewLink.href = imageInfo.newfile;
file._viewLink.name = imageInfo.newfile;
$scope.$apply(function() {
$scope.component.image="rest/components/"+$scope.component.name+"/"+$scope.component.version+"/"+imageInfo.newfile;
});
});
二、页面中的图片怎样进行回显?
1、现今的站点上图片上的获取方式主要是以Get请求的方式传回图片流到浏览器端,这里相同採用请求主动获取图片的方式。
页面回显时会主动发送请求:
“rest/components/”+scope.component.name+"/"+scope.component.version +”/”+$scope.component.image
真实请求路径是这种:
localhost:8080/xxxxxx/rest/components/2_component1/1.0.0/0c6684ad-84df-4e0e-8163-9e2d179814e6-Penguins.jpg
2、后台怎样接受请求,处理请求呢?
參见下面代码,返回到浏览器的实际上就是一个输出流。
关键代码演示样例
/**
* get pictures OutputStream
*
* @param componentName
* @param version
* @return
*/
@GET
@Path("/{componentName: \\w+}/{version: \\d\\.\\d\\.\\d}/{imagePath: .+}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response findImages(@PathParam("componentName") final String componentName, @PathParam("version") final String version,
@PathParam("imagePath") final String imagePath) {
StreamingOutput output = new StreamingOutput() {
private BufferedInputStream bfis = null;
public void write(OutputStream output) throws IOException, WebApplicationException {
try {
String filePath = "";
//推断图片的请求路径是否长路径,这个依据需求而来的
if (imagePath.contains("/")) {
//取出图片
filePath = application.getStorageLocation(File.separator + componentName + File.separator + version) + File.separator + "img"
+ File.separator + imagePath.split("/")[imagePath.split("/").length - 1];
} else {
//取出图片
filePath = application.getStorageLocation(File.separator + componentName + File.separator + version) + File.separator + "img"
+ File.separator + imagePath;
}
bfis = new BufferedInputStream(new FileInputStream(filePath));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = bfis.read(bytes)) != -1) {
output.write(bytes, 0, read);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bfis != null) {
bfis.close();
}
output.flush();
output.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
};
//返回给浏览器
return Response.ok(output, MediaType.APPLICATION_OCTET_STREAM).build();
}
3、当点击view时。又会去请求后台返回预览大图图像,这里使用了colorbox插件来进行大图像的预览和轮播显示。感觉非常酷的样子。
效果例如以下所看到的:
使用Dropzone上传图片及回显演示样例的更多相关文章
- 通过Canvas及File API缩放并上传图片完整演示样例
创建一个只管的用户界面,并同意你控制图片的大小.上传到server端的数据,并不须要处理enctype为 multi-part/form-data 的情况.只一个简单的POST表单处理程序就能够了. ...
- 【UNIX网络编程(三)】TCP客户/server程序演示样例
上一节给出了TCP网络编程的函数.这一节使用那些基本函数编写一个完毕的TCP客户/server程序演示样例. 该样例运行的过程例如以下: 1.客户从标准输入读入一行文本,并写给server. 2.se ...
- 移动端报表JS开发演示样例
近期对移动端的报表开发颇有研究,细磨精算了好久,尽管到如今还是"囊中羞涩",但决定还是先抛砖引玉,拿点小干货出来和大家分享. 研究的工具是比較有代表性的FineReport. 1. ...
- Cocos2d-x 3.1.1 Lua演示样例 ActionEaseTest(动作)
Cocos2d-x Lua演示样例 ActionEaseTest(动作) 本篇博客介绍Cocos2d-x中的动作,Cocos2d-x为我们提供了丰富的动作接口,以下笔者就具体介绍一下: 本系列 ...
- 最简单的视音频播放演示样例4:Direct3D播放RGB(通过Texture)
===================================================== 最简单的视音频播放演示样例系列文章列表: 最简单的视音频播放演示样例1:总述 最简单的视音频 ...
- RHEL5 X86-64上安装Oracle 11gR2演示样例与总结
进入Oracle DBA行业也有好几年了,可是说到安装Oracle的经验,我还真不是特别多,印象中刚開始每次安装都有点磕磕碰碰,随着接触Oracle的时间越来越长,各方面的原理.机制也都有一定的了解后 ...
- java文件夹相关操作 演示样例代码
java文件夹相关操作 演示样例代码 package org.rui.io; import java.io.File; import java.io.FilenameFilter; import ja ...
- 10分钟理解Android数据库的创建与使用(附具体解释和演示样例代码)
1.Android数据库简单介绍. Android系统的framework层集成了Sqlite3数据库.我们知道Sqlite3是一种轻量级的高效存储的数据库. Sqlite数据库具有以下长处: (1) ...
- 01_MUI之Boilerplate中:HTML5演示样例,动态组件,自己定义字体演示样例,自己定义字体演示样例,图标字体演示样例
1安装HBuilder5.0.0,安装后的界面截图例如以下: 2 依照https://www.muicss.com/docs/v1/css-js/boilerplate-html中的说明,创建上 ...
随机推荐
- 如何让 ssh 允许以 root 身份登录
默认情况下,Pack 上的 root 用户不能用通过密码来远程登录,可以用一下命令来做:(注意要在 root 权限下) sed -i 's/PermitRootLogin\swithout-passw ...
- <vim实用技巧>学习笔记
第三章插入模式 1.插入模式下的删除 2.返回普通模式 3.复制 yt, //复制当前光标到逗号(,)之前的内容 第四章 可视模式 1 ...
- P1025小飞侠的游园方案
描述 经过抽签选择,小智将军第一个进入考场. 菜虫:(身上散射出华贵(?)的光芒)欢迎你,第一位挑战者!! 小智:……(走到菜虫身后,关灯)女王陛下,虽然我们国家现在很富裕,但也请您不要浪费电来用这么 ...
- Hdu-5992 2016ACM/ICPC亚洲区青岛站 K.Finding Hotels KDtree
题面 题意:二维平面上有很多点,每个点有个权值,现在给你一个点(很多组),权值v,让你找到权值小于等于v的点中离这个点最近的,相同的输出id小的 题解:很裸的KDtree,但是查询的时候有2个小限制, ...
- 关于c-string类
特别鸣谢:由张老师整理(原出处未知 一.C++ 字符串 C++ 提供了以下两种类型的字符串表示形式: C 风格字符串 C++ 引入的 string 类类型 1.C 风格字符串 C 风格的字符串起源于 ...
- Hadoop MapReduce编程 API入门系列之join(二十六)(未完)
不多说,直接上代码. 天气记录数据库 Station ID Timestamp Temperature 气象站数据库 Station ID Station Name 气象站和天气记录合并之后的示意图如 ...
- python 模块导入详解
本文不讨论 Python 的导入机制(底层实现细节),仅讨论模块与包,以及导入语句相关的概念.通常,导入模块都是使用如下语句: import ... import ... as ... from .. ...
- for循环和数组的应用
<html> <head> <meta charset="utf-8"> <title>无标题文档</title> &l ...
- MSSQL数据库设置单用户模式后无法连上解决办法
设置数据库单用户模式后, 发现用系统管理员账号无法连接数据库, 用sa账号也不行. 首先, 马上去查了一下有什么进程比这个连接给占用了 SELECT [Spid] = session_Id , eci ...
- 杭电2602 Bone Collector 【01背包】
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2602 解题思路:给出一个容量为V的包,以及n个物品,每一个物品的耗费的费用记作c[i](即该物品的体积 ...