您的位置:首页 > Web前端 > JavaScript

js实现文件的上传和直接预览(不经过服务端)

2017-01-09 17:11 435 查看
js实现文件的上传,注意要使用BASE64编码!
<div  class="bottom-border mt10">
<input type="hidden" id="imgcodeBusiness" value=""/>
<input type="hidden" id="imgUrlBusiness" value=""/>
<h5 class="color1 font-weight-normal" style="width:50%;"></h5>上传图片
</div>
<div id="imguploadBusiness" style="overflow-y:auto;">
<div class="addImg" id="addImgBusiness"></div>
<div class="addF" style="margin-top:10px;">
<input accept="image/*" type="file" class="addFm" id="upLoadBusiness"/>
</div>
<!--  <input accept="image/*" type="file" class="addFm" id="upLoadBusiness"/> -->
</div>
js代码$("#upLoadBusiness", parent.document).unbind("change").bind("change",(function(e) {
var imgcode = $("#imgcodeBusiness", parent.document).val();
var that = this.files[0];
var type = ((that.type).split('/'))[1];
controller.run(this, function(data) {
var img = new Image(), div = document.createElement('div');
img.style.width = '100px';
img.style.height = '100px';
div.appendChild(img);
parent.document.getElementById("addImgBusiness",parent.document).appendChild(div);
img.src = data;
img.onclick = function() {
window.open(data);
}
cpic.ajax("task/taskUploadImg" + "?t="+ new Date().getTime(), {
type : type,
base64 : data,
imgcode : imgcode
}, function(data) {
if(data.returnUrl!=null && data.returnUrl!=undefined && data.returnUrl!=""){
$("#imgUrlBusiness", parent.document).val(data.returnUrl);
}
}, function() {
});
});

}));
this.run = function(input_file, get_data) {
/* input_file:文件按钮对象 */
/* get_data: 转换成功后执行的方法 */
if (typeof (FileReader) === 'undefined') {
alert("抱歉,你的浏览器不支持 FileReader,不能将图片转换为Base64,请使用现代浏览器操作!");
} else {
try {
/* 图片转Base64 核心代码 */
var file = input_file.files[0];
// 这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
if (!/image\/\w+/.test(file.type)) {
alert("请确保文件为图像类型");
return false;
}
var reader = new FileReader();
reader.onload = function() {
get_data(this.result);
}
reader.readAsDataURL(file);
} catch (e) {
alert('图片转Base64出错啦!' + e.toString())
}
}
};
后台代码

/**
* 上传图片
*
* @param requestBody
* @return
* @throws Exception
*/
@RequestMapping(value = "taskUploadImg", produces = "application/json")
@ResponseBody
public Map<String, Object> taskUploadImg(
@RequestBody Map<String, Object> requestBody) throws Exception {
Map<String, Object> resultMap = new HashMap<String, Object>();

String base64 = (String) requestBody.get("base64");
String downimgcode = (String) requestBody.get("imgcode");
String type = (String) requestBody.get("type");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String formatDate = sdf.format(new Date());
if (downimgcode != "" && downimgcode != null) {
type = type.substring(type.indexOf(".") + 1);
CodeEntryEO codeEntryEO = dataCacheManager.getCodeEntryCacheByName(
"image", "uploadPath");
String uploadPathStr = "";
if (codeEntryEO != null) {
uploadPathStr = codeEntryEO.getExtendType();
}
if (!uploadPathStr.endsWith("/")) {
uploadPathStr = uploadPathStr + "/";
}
String uploadPath = uploadPathStr + "uploadFile/business_img/"
+ formatDate + "/" + downimgcode + "/";
// 检查上传文件的目录
File uploadDir = new File(uploadPath);
// deleteFile(uploadDir);
if (!uploadDir.exists()) {// 判断文件夹是否创建,没有创建则创建新文件夹
uploadDir.mkdirs();
}
// 新文件名
String newname = DateUtil.DateTimeNumber() + "." + type;
resultMap.put("herf", uploadPath + newname);
Base64Decoder decoder = new Base64Decoder();
File imageFile = new File(uploadPath, newname);
// 创建输出流
FileOutputStream outputStream = new FileOutputStream(imageFile);
try {

// 获得一个图片文件流,我这里是从flex中传过来的
byte[] img = decoder.decode(base64.split(",")[1]);// 解码
for (int i = 0; i < img.length; ++i) {
if (img[i] < 0) {// 调整异常数据
img[i] += 256;
}
}
outputStream.write(img);
} catch (Exception e) {
} finally {
if (outputStream != null) {
outputStream.close();
}
}
resultMap.put("returnUrl", uploadPath);
}

return resultMap;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: