JS 上传图片 + 预览功能(一)

JS 上传图片 + 预览功能

<body> 
<input type="file" id="fileimg1" style="display:none;" />
<img src="../image/upimg.png" id="upimg1" style=" height: 300px; width:280px;" />
<input type="button" value="选择" onclick="selimg();" />
<input type="button" value="上传" onclick="upimg();" /> 
</body>

<script> 
function selimg() {
$("#file").click();

};
function upimg() {

var fileObj = document.getElementById("fileimg1").files[0]; // js 获取文件对象

// 预览功能
var imgphy1 = getObjectURL(fileObj);
if (imgphy1) {
$("#upimg1").attr("src", imgphy1); //将图片路径存入src中,显示出图片
}

//上传方法一 :

if (fileObj != undefined) {
var form = new FormData(); // FormData 对象
form.append("file", fileObj, "newname.jpg"); // 文件对象 
var ajaxRequest = $.ajax({
type: "POST", 
url: "http://eplate_mobile.zwtweb.win:83/anju/Web/eplate/picupload.php", /// 跨域上传
contentType: false,
processData: false,
async: true,
data: form,
success: function (data) {
console.log(data);
// alert(data);
var str = data;
console.log(str.search("上传成功") != -1); // true
if (str.search("上传成功") != -1) { 
alert("上传成功 ") 
}

else {
alert("上传失败 ") 
}
}
});

//上传方法二 :
var data = new FormData(); // 实例化一个表单数据对象
var files = $('#fileimg1').get(0).files; 
if (files.length > 0) {
data.append("ImgFile", files[0]);
data.append("act", "addAnlizw");
}

var ajaxRequest = $.ajax({
type: "POST",
url: "../web_Set/ajaxFileUpload.ashx", // 本域上传图片
contentType: false,
processData: false,
async: true,
data: data,
success: function (data) {
if (data != null && data != "") { 
alert("上传图片成功")
}
else {
alert("上传图片失败")
}
}
});

}

//建立一個可存取到該file的url
function getObjectURL(file) {
var url = null;
if (window.createObjectURL != undefined) { // basic
url = window.createObjectURL(file);
} else if (window.URL != undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file);
}
return url;
}
</script>

上一篇:jQuery 遍历方法


下一篇:检查Linux服务器性能的关键十条命令