我怎么能看到一个预览上传的图像(don!),然后保存它的地址
本文关键字:图像 don 然后 地址 保存 怎么能 一个 | 更新日期: 2023-09-27 17:51:26
我想上传一张图片但首先我想看到图像的预览,然后当用户点击另一个asp:button
时,保存图像。
<script src="//code.jquery.com/jquery.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script>
jQuery(document).ready(function ($) {
$('#image').on('change', function (event) {
var image = this.files[0];
$('#singlePreview').html('');
var reader = new FileReader();
reader.onload = function (e) {
$('<img src="' + e.target.result + '" class="thumbnail img-responsive" width="150" alt="Loading..">').appendTo($('#singlePreview'));
}
reader.readAsDataURL(image);
});
});
</script>
,
<div class="form-group">
<label for="image">image</label>
<input type="file" id="image" accept="image/*" />
</div>
<div id="singlePreview"></div>
但现在我不知道如何保存上传的图像URL。因为我对JavaScript和jquery一窍不通。
我知道this.files[0]
是我的地址。但是我想在代码后面使用它(c#)
你可以通过ajax调用来上传图片
// var file;
$('#image').on('change', function (event) {
var image = this.files[0];
$('#singlePreview').html('');
var reader = new FileReader();
reader.onload = function (e) {
$('<img src="' + e.target.result + '" class="thumbnail img-responsive" width="150" alt="Loading..">').appendTo($('#singlePreview'));
}
reader.readAsDataURL(image);
//file=this.files[0];
});
//This is your button click
$("#btnUpload").on('click',function(){
uploadFile();
});
function uploadFile() {
var formData = new FormData();
formData.append('file', $('#image')[0].files[0]);
$.ajax({
type: 'post',
url: 'pathTo/genericHandler.ashx',
data: formData,
success: function (status) {
alert("Success")
},
error function (status) {
alert("Failed!");
},
processData: false,
contentType: false
});
}
背后的代码:首先,需要在应用程序中添加通用处理程序(ashx文件)。下面的代码将保存上传的文件
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
try
{
string dirFullPath = HttpContext.Current.Server.MapPath("~/MediaUploader/");
string[] files;
int numFiles;
files = System.IO.Directory.GetFiles(dirFullPath);
numFiles = files.Length;
numFiles = numFiles + 1;
string str_image = "";
foreach (string str in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[str];
string fileName = file.FileName;
string fileExtension = file.ContentType;
if (!string.IsNullOrEmpty(fileName))
{
fileExtension = Path.GetExtension(fileName);
str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
string pathToSave = HttpContext.Current.Server.MapPath("~/MediaUploader/") + str_image;
file.SaveAs(pathToSave);
}
}
// database record update logic here ()
context.Response.Write(str_image);
}
catch (Exception ac)
{
}
}