简单实现jQuery和Ajax的图片/文件上传与下载
1,上传图片
这两句句是必须的
processData: false,//不处理
contentType: false,//非默认
实现代码"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片上传示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("#uploadForm").submit(function(e) {
e.preventDefault();
var formData = new FormData();
var imageFile = $("#image")[0].files[0];
formData.append("Appname", "444");//一些参数
formData.append("PageName", "444");
formData.append("language", "444");
formData.append("ImageName", "444");
formData.append("file", imageFile);
$.ajax({
url: "http://localhost:44341/imageapi/api/v3/Image/UploadImage",
// url: "http://192.168.110.159:7400/ImageApi/api/v3/Image/UploadImage",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(response) {
// 处理上传成功的响应
console.log("欧克"+response);
},
error: function(xhr, status, error) {
// 处理上传失败的情况
console.log("Error:", error);
}
});
});
});
</script>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="image" id="image">
<button type="submit">上传图片</button>
</form>
</body>
</html>
2.图片下载显示
如果后端传的是文件流,需要将数据解释为二进制大对象(blob)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>下载并显示图片示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("#downloadButton").click(function() {
var formData = new FormData();
formData.append("Appname", "444");//一些参数
formData.append("PageName", "444");
formData.append("language", "444");
formData.append("ImageName", "444");
$.ajax({
url: "http://localhost:44341/ImageApi/api/v3/Image/DownloadImage",
type: "POST", // 使用POST方法,同时发送FormData
data: formData,
processData: false,
contentType: false,
xhrFields: {
responseType: "blob" //二进制
},
success: function(response) {
// 创建一个 Blob 对象的 URL,以便设置给 <img> 标签的 src 属性
var imageURL = URL.createObjectURL(response);
$("#downloadedImage").attr("src", imageURL);
console.log(response.type);
console.log(response);
},
error: function(xhr, status, error) {
// 处理下载失败的情况
console.log("Error:", error);
}
});
});
});
</script>
</head>
<body>
<button id="downloadButton">下载并显示图片</button>
<br>
<img id="downloadedImage" alt="下载的图片">
</body>
</html>
文件同理