[英]how to upload image to server side using JQuery ajax and without library using asp.net webform?
Hellow,你好,
I found a code that allows me to drag and drop an image to be displayed in a zone.我找到了一个代码,它允许我拖放要在区域中显示的图像。 and it works successfully.它工作成功。 However, after many trials, I couldn't be able to upload the file.但是,经过多次试验,我无法上传文件。 I know the path is will be fake and it is not allowed to be retrieved.我知道路径是假的,不允许检索。
I have tried to use JQuery Ajax to trigger a method "DataSave" that should use fileupload tool to save the included image.我尝试使用 JQuery Ajax 来触发一个方法“DataSave”,该方法应该使用文件上传工具来保存包含的图像。 however, it returns null !!但是,它返回 null !
what would be the solution to save this image at the server?将此图像保存在服务器上的解决方案是什么?
HTML HTML
<div id="dropzone">
<div>dropzone</div>
<asp:FileUpload ID="FileUploadControl" runat="server" />
</div>
<asp:Label ID="StatusLabel" runat="server" Text="Label"></asp:Label>
CSS CSS
<style>
#dropzone {
position: relative;
border: 5px dotted #000;
border-radius: 10px;
color: #000;
font: bold 24px/200px arial;
height: 200px;
margin: 30px auto;
text-align: center;
width: 200px;
}
#dropzone.hover {
border: 4px solid green;
color: green;
}
#dropzone.dropped {
background: #222;
border: 5px solid #444;
}
#dropzone div {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
#dropzone img {
border-radius: 5px;
vertical-align: middle;
max-width: 95%;
max-height: 95%;
}
#dropzone [type="file"] {
cursor: pointer;
position: absolute;
opacity: 0;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
</style>
JavaScript JavaScript
<script>
$(function () {
var dropzone = $("#dropzone"),
input = dropzone.find('input');
dropzone.on({
dragenter: dragin,
dragleave: dragout
});
input.on('change', drop);
function dragin(e) { //function for drag into element, just turns the bix X white
$(dropzone).addClass('hover');
}
function dragout(e) { //function for dragging out of element
$(dropzone).removeClass('hover');
}
function drop(e) {
var file = this.files[0];
$('#dropzone').removeClass('hover').addClass('dropped').find('img').remove();
// upload file here
showfile(file); // showing file for demonstration ...
}
function showfile(file) {
//var fd = new FormData();
//var files = file;
//fd.append('file', files);
var reader = new FileReader(file);
reader.readAsDataURL(file);
reader.onload = function (e) {
$('#dropzone div').html($("<img id='img' />").attr('src', e.target.result).fadeIn());
};
$.ajax({
type: "POST",
url: "dragapleImage.aspx/DataSave",
<%-- data: '{MyImg: "' + $("#<%=FileUploadControl.ClientID%>")[0].value + '" }',--%>
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
function OnSuccess(response) {
alert(response.d);
}
};
});
</script>
C# C#
[WebMethod]
public static string DataSave(string MyImg)
{
HttpPostedFile fileup = HttpContext.Current.Request.Files["FileUploadControl"];
string filename = Path.GetFileName(fileup.FileName);
fileup.SaveAs("~/" + filename);
return "Upload status: File uploaded!";
}
Try this:尝试这个:
var formData = new FormData();
formData.append('file', $('#FileUploadControl')[0].files[0]);
$.ajax({
type: 'post',
url: 'saveImage.ashx',
data: formData,
success: function (status) {
if (status != 'error') {
alert("ok!");
}
},
processData: false,
contentType: false,
error: function () {
alert("Sorry!");
}
});
EDIT:编辑:
You can add a generic hundler in the server side (ashx file).您可以在服务器端(ashx 文件)中添加一个通用的 hundler。 It will look like this (name it saveImage.ashx and don't forget to change &.ajax url!):它看起来像这样(将其命名为 saveImage.ashx 并且不要忘记更改 &.ajax url!):
using System;
using System.Web;
using System.IO;
public class fileUploader : IHttpHandler {
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 s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
string fileName = file.FileName;
string fileExtension = file.ContentType;
if (!string.IsNullOrEmpty(fileName))
{
fileExtension = Path.GetExtension(fileName);
str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
string pathToSave_100 = HttpContext.Current.Server.MapPath("~/MediaUploader/") + str_image;
file.SaveAs(pathToSave_100);
}
}
// database record update logic here ()
context.Response.Write(str_image);
}
catch (Exception ac)
{
}
}
public bool IsReusable {
get {
return false;
}
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.