hello everybody I'm new here and I'm new to jquery too
I apply this article to my website to upload multiple data at once
using-dropzone-js-file-image-upload-in-asp-net-webform-c
while I'm using this code when I click on the dropzone area it's uploading the photos directly to ~/work/
so what I hope so is to use a button with id=post
to upload these images in dropzone area only after click on it
so here is my code:
here is the header:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link href="css/dropzone.css" rel="stylesheet" type="text/css" />
<script src="js/dropzone.js" type="text/javascript"></script>
the html part:
<div id="dZUpload" class="dropzone ">
<div class="dz-default dz-message"></div>
</div>
the javascript part:
<script>
$(document).ready(function () {
Dropzone.autoDiscover = false;
//Simple Dropzonejs
$("#dZUpload").dropzone({
url: 'FileUploader.ashx',
addRemoveLinks: true,
maxFiles: 3,
success: function (file, response) {
var imgName = response;
file.previewElement.classList.add("dz-success");
console.log("Successfully uploaded :" + imgName);
},
error: function (file, response) {
file.previewElement.classList.add("dz-error");
}
});
});
</script>
and finally the Generic Handler "
FileUploader.ashx
:
<%# WebHandler Language="C#" Class="FileUploader" %>
using System;
using System.Web;
using System.IO;
public class FileUploader : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string dirFullPath = HttpContext.Current.Server.MapPath("~/work/");
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];
// int fileSizeInBytes = file.ContentLength;
string fileName = file.FileName;
string fileExtension = file.ContentType;
if (!string.IsNullOrEmpty(fileName))
{
fileExtension = Path.GetExtension(fileName);
str_image = "WorkPhoto_" + numFiles.ToString() + fileExtension;
string pathToSave_100 = HttpContext.Current.Server.MapPath("~/work/") + str_image;
file.SaveAs(pathToSave_100);
}
}
context.Response.Write(str_image);
}
public bool IsReusable {
get {
return false;
}
}
}
Here i think this will solve your Problems:
<script>
$(document).ready(function () {
Dropzone.autoDiscover = false;
//Simple Dropzonejs
var myDropzone = new Dropzone("#dZUpload", {
url: 'FileUploader.ashx', autoProcessQueue: false, addRemoveLinks: true, maxFiles: 3,
success: function (file, response) {
var imgName = response;
file.previewElement.classList.add("dz-success");
console.log("Successfully uploaded :" + imgName);
},
error: function (file, response) {
file.previewElement.classList.add("dz-error");
},
});
$('#button').on('click', function (e) {
myDropzone.processQueue();
});
});
Related
Im Stuck with the problem that I can't get the "UploadMultiple" to work.
Whenever I try to Drop more than one File at once (drag and dropp 3 selected PDF files for example) I don't recieve any files in the c# controller.
The View seems to work, as there are no errors when dropping the Files.
In the controller however, I don't recieve any files (files.Count = 0).
these are my code snippets:
View HTML:
<div class="col-md-8">
<form id="fileUploadForm" class="text-center dropzone needsclick dz-clickable" method="post" enctype="multipart/form-data" style="min-height: 500px;">
</form>
</div>
JS:
Dropzone.autoDiscover = false;
$("#fileUploadForm").dropzone({
url: "/UploadView",
paramName: "files",
uploadMultiple: true,
parallelUploads: 1,
maxFilesize: 50,
init: function () {
this.on('success', function (file) {
var element = document.getElementById("submitbutton");
element.style.display = "inline";
var args = Array.prototype.slice.call(arguments);
var lowercaseName = file.name.toLowerCase()
if (!lowercaseName.includes(".pdf") && args[1] === "success") {
$("#directUploadDocs").append("<p>" + file.name + "</p><br />");
} else {
switch (args[1]) {
case "HashFailed":
$("#errorDocs").append("<div><h4>CUSTOM_TEXT</h4><p>" + file.name + "</p></div>");
break;
case "UnknownFile":
$("#errorDocs").append("<div><h4>CUSTOM_TEXT</h4><p>" + file.name + "</p></div>");
break;
case "success":
console.log("success");
break;
default:
console.log("sorry an error happened");
}
}
});
},
});
C# Controller:
public async Task<IActionResult> OnPostAsync(ICollection<IFormFile> files)
{
var directoryPath = Path.Combine(_appSettings.UploadFolder, user.SessionID);
Directory.CreateDirectory(directoryPath);
foreach (var file in files)
{
var uploadPath = Path.Combine(_appSettings.UploadFolder, user.SessionID, Guid.NewGuid().ToString() + Path.GetExtension(file.FileName));
if (file.Length > 0)
{
Do Something;
}
}
return Content("success");
}
I know that I wrote pretty custom code additional to the reccomended code from dropzone.js, but I hope its still possible to fix that Problem.
SOLVED!
SOLUTION:
Bruce Adams Posted an answer that actually worked for me:
new C# controller:
public async Task<IActionResult> OnPostAsync()
{
var directoryPath = Path.Combine(_appSettings.UploadFolder, user.SessionID);
Directory.CreateDirectory(directoryPath);
foreach (var file in Request.Form.Files)
{
var uploadPath = Path.Combine(_appSettings.UploadFolder, user.SessionID, Guid.NewGuid().ToString() + Path.GetExtension(file.FileName));
if (file.Length > 0)
{
Do Something;
}
}
return Content("success");
}
I want to upload some files to iis 7 by formdata with ajax ,but they are cut into less than 80kb,while it’s alright in debug mode
It can work correctly when the first time I run the IIS, only once.
there is the source code of Up.html, I have removed all the useless function:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="../../js/jquery-1.4.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
function UploadFiles() {
var formData = new FormData();
var files = $('#fileExcel')[0].files;
for (var i = 0; i < files.length; i++) {
formData.append("file[]", files[i]);
}
$.ajax({
url: 'Up.ashx',
type: 'POST',
data: formData,
async: false,
cache:false,
processData: false,
contentType: false,
success: function() {
formData = null;
}
});
}
</script>
</head>
<body>
<form action="Up.ashx" method="post"></form>
<input id="fileExcel" name="file" type="file" multiple="multiple"/>
<button id="btnUpload" onclick="UploadFiles()">上传</button>
</body>
</html>
And there is the code of Up.ashx,I have removed all the useless function:
using System.IO;
using System.Web;
public class Up : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
HttpFileCollection files = context.Request.Files;
if (files.Count<1)
{
context.Response.Write("no file");
context.Response.End();
}
string category = this.GetType().ToString();
string filePath = HttpContext.Current.Server.MapPath("~/FileUpload/" + category + "/");
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
file.SaveAs(filePath+file.FileName);
}
context.Response.Write(files.Count + " files");
context.Response.End();
}
public bool IsReusable {
get {
return false;
}
}
}
When I modified the code like this, it works, I just don't know why.
public Dictionary<string,string> ReceiveFiles(HttpContext context)
{
// return files info as Dictionary
Dictionary<string,string> result = new Dictionary<string, string>();
string category = this.GetType().ToString();
string filePath = HttpContext.Current.Server.MapPath("~/FileUpload/" + category + "/");
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
// the key statement👇,I just don't know why it works
string savePath = context.Request["path"];//"path" can be instead to any keystring,T^T!
string[] files = context.Request.Files.AllKeys;
foreach (string str in files)
{
HttpPostedFile file = context.Request.Files.Get(str);
try
{
file.SaveAs(filePath + file.FileName);
result.Add(file.FileName,filePath+file.FileName);
//context.Response.Write("上传成功!");
}
catch (Exception ex)
{
context.Response.Write("上传失败!错误信息:" + ex.Message.ToString());
return null;
}
}
return result;
}
I am trying to insert multiple images in a single row in a field in oracle database, please suggest how to achieve it. Below are the details
image is rendering on the browser and I want to store multiple image through it in oracle db. Each image will have an id generating dynamically
aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html>
<head>
<style>
input[type="file"] {
display:block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
margin: 10px 10px 0 0;
padding: 1px;
}
</style>
<title></title>
</head>
<body>
<form id="form1" runat="server">
Find the bellow HTML code
<h2>preview multiple images before upload using jQuery</h2>
<input type="file" id="files" name="files[]" multiple />
<asp:Button ID="Button3" runat="server" BorderColor="#CCFF66"
ForeColor="#0066FF" Text="Insert Data" />
</form>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var a = 0;
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function (e) {
var files = e.target.files,
filesLength = files.length;
if (filesLength == 1) {
a = a + 1;
}
for (var i = 0; i < filesLength ; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function (e) {
var file = e.target;
$("<img></img>", {
class: "imageThumb",
Id: "img"+ a.toString(),
src: e.target.result,
title: file.name
}).insertAfter("#files");
});
fileReader.readAsDataURL(f);
}
});
} else { alert("Your browser doesn't support to File API") }
});
</script>
</body>
</html>
for saving image into oracle db I am using ajax and created webservice to push data into db:
[WebMethod]
public static void SaveUser(User user)
{
String connectionString = ConfigurationManager.ConnectionStrings["conndbprodnew"].ConnectionString;
using (OracleConnection con = new OracleConnection(connectionString))
{
using (OracleCommand cmd = new OracleCommand("INSERT INTO par_cinfo(Product_Id,IMAGETYPE ) VALUES (:IMAGETYPE )", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("IMAGETYPE ", user.IMAGETYPE);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
public class User
{
public decimal Product_Id { get; set; }
public Image IMAGETYPE { get; set; }
}
jQuery ajax on button click to send data to webservices:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=Button3]").bind("click", function () {
var user = {};
user.Product_Id = 1;
user.IMAGETYPE= "here dynamic image id which is uploaded should be present "
$.ajax({
type: "POST",
url: "Default.aspx/SaveUser",
data: '{user: ' + JSON.stringify(user) + '}',
//data: JSON.stringify({user:user}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
return false;
});
});
</script>
The table which I created in oracle is as follows simply for entering the data in the table:
Create table par_cinfo
(
Product_Id NUMBER(10) NOT NULL PRIMARY KEY,
IMAGETYPE BLOB
)
I am trying to pass some JavaScript variable value from .aspx file to .ashx file when user uploads a document in the web form.
The web form is a .aspx file and the uploading functionality is in .ashx file. So I need to pass the variables from .aspx file to .ashx file.
I was able to pass three variables but when I try to pass the fourth one then it does not work. It does not give any error but just do not pass any of the variables. When I debug the code I can see the debugger does not enters the process of upload. And the upload button also changes
This is my .aspx page code.
<%# Page Title="" Language="VB" MasterPageFile="~/_resx/E4.master" AutoEventWireup="true" CodeFile="new.aspx.vb" Inherits="E4_Jobs_new" ValidateRequest="false" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server">
<script type="text/javascript">
var id = '<%= ModeID%>', mode = '<%= Mode%>', employer = '<%= Employer.Name %>', jtitle = document.getElementById(<%= txtTitle.ClientID%>);
</script>
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtTitle" Display="None" ErrorMessage="xx" ValidationGroup="NewJob" EnableViewState="False" />
<div class="form-element">
<input type="text" id="txtTitle" runat="server" maxlength="64" /></div>
<div class="m-accor-body">
<ul id="attachmentList">
<% For Each additionalDoc As DataRow In Vacancy.Attachemnts.Rows%>
<li id="da<%= additionalDoc.Item("id") %>">
<span><%= additionalDoc.Item("name") %></span>
<span class="rd" data-did="<%= additionalDoc.Item("id")%>"> remove</span>
</li>
<%Next%>
</ul>
<div id="queue"></div>
<input id="file_upload" name="file_upload" type="file">
</div>
</asp:Content>
And this is the code in the .aspx file where I am passing the variables into .ashx file
$(function () {
dimNav('vacancy');
$('#file_upload').uploadify({
'buttonClass': 'button2',
'buttonText': 'Select a PDF or DOCX file to upload..',
'width': 250,
'fileTypeExts': '*.pdf; *.doc; *.docx',
'formData': {
'draftId': id,
'type': mode,
'employer': employer,
'jtitle': jtitle
},
'uploadLimit': 6,
'swf': '/_resx/uploadify.swf',
'uploader': '/e4/jobs/upload-job-attachments.ashx',
'onUploadSuccess': function (file, data, response) {
$('#attachmentList').append('<li id="da' + data + '"><span>' + file.name + '</span><span class="rd" data-did="' + data + '"> remove</span></li>');
}
});
});
The first three variables values are obtained differently than the fourth one. In the fourth one I used javascript function to get the value (as it is the input value given by the user. Not a value stored already in database. ) .
This is my code for in the upload-job-attachments.ashx file where I retrieve the values
Public Class upload_job_attachments : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
context.Response.Expires = -1
Try
Dim Id As Integer = CInt(context.Request("draftid"))
Dim type As String = CStr(context.Request("type"))
Dim empname As String = CStr(context.Request("employer"))
Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")
********** other lines of code ***********
End Sub
End Class
what can I do to overcome the problem. I am weak in advanced javascript functionalities. I appreciate your help
Addition
The whole script looks like
$(function () {
dimNav('vacancy');
var jobTitle = $('#' + '<%= txtTitle.ClientID%>').val();
$('#file_upload').uploadify({
'buttonClass': 'button2',
'buttonText': 'Select a PDF or DOCX file to upload..',
'width': 250,
'fileTypeExts': '*.pdf; *.doc; *.docx',
'formData': {
'draftId': id,
'type': mode,
'employer': employer,
'jtitle': jobTitle
},
'uploadLimit': 6,
'swf': '/_resx/uploadify.swf',
'uploader': '/e4/jobs/upload-job-attachments.ashx',
'onUploadSuccess': function (file, data, response) {
$('#attachmentList').append('<li id="da' + data + '"><span>' + file.name + '</span><span class="rd" data-did="' + data + '"> remove</span></li>');
alert($('#' + '<%= txtTitle.ClientID%>').val());
}
});
$('body').on('click', '.rd', function () {
var el = $(this);
$.post('delete-job-attachment.ashx?id=' + el.attr('data-did'), '{}', function () {
$('#da' + el.attr('data-did')).remove();
});
});
$('.price-button').click(function () { $(this).next('.price-list').fadeToggle('slow'); });
$('.m-lists table tr:nth-child(4) td:nth-child(1)').prepend('<div>Multiple job posting</div>');
$('.jMedias').change(function () {
suffleMedias();
});
var suffleMedias = function () {
var mids = [];
$('.jMedias:checked').each(function () {
mids.push($(this).val());
});
$('.mediaLists').val(mids.toString());
};
$('.jType').change(function () {
suffleJobType();
});
$('input:radio.p-option-radio').change(function () {
var pOption = $(this).val();
$('.p-option').val(pOption);
});
var suffleJobType = function () {
var type = $('.jType').val();
if (type == 0) {
$('#contractLength, #jobHour').slideUp();
} else if (type == 1) {
$('#jobHour').slideDown();
$('#contractLength').slideUp();
} else if (type == 2) {
$('#jobHour').slideDown();
$('#contractLength').slideUp();
} else if (type == 3) {
$('#contractLength, #jobHour').slideDown();
}
};
var suffleFeeType = function () {
var fType = $('.feeType').val();
if (fType == 0) {
$('#salaryRateMax, #salaryRateMin, #agencyFee').slideDown();
} else if (fType == 1) {
if (parseFloat($('.referrerPercentage option:selected').text()) > 0) {
} else {
$('#salaryRateMax, #salaryRateMin').slideUp();
}
$('#agencyFee').slideDown();
} else if (fType == 2) {
$('#agencyFee').slideUp();
if (parseFloat($('.referrerPercentage option:selected').text()) > 0) {
} else {
$('#salaryRateMax, #salaryRateMin').slideUp();
}
}
};
$('.feeType').change(function () {
suffleFeeType();
});
$('.referrerPercentage').change(function () {
if (parseFloat($('.referrerPercentage option:selected').text()) > 0) {
$('#salaryRateMax, #salaryRateMin').slideDown();
} else {
if ($('.feeType').val() == 1) {
$('#salaryRateMax, #salaryRateMin').slideUp();
}
}
});
$('.calcFee').change(function () {
CalculateAndDisplayFees();
});
$('.rAgency').chosen().change(function () {
if ($(this).val() != '-1') {
$('.psls').val('-1').trigger("liszt:updated");
$('.retained').val('1');
}
});
$('.psls').chosen().change(function () {
if ($(this).val() != '-1') {
$('.rAgency').val('-1').trigger("liszt:updated");
$('.retained').val('0');
}
});
var setPublishOption = function () {
var p = $('.p-option').val();
var $radios = $('input:radio.p-option-radio');
$radios.filter('[value=' + p + ']').attr('checked', true);
};
suffleJobType();
suffleFeeType();
suffleMedias();
CalculateAndDisplayFees();
setPublishOption();
});
If, for instance, the jtitle field needs to come from an input control, you can do:
'formData': {
'jtitle': $("#somecontrol").val()
}
Which will get the value from a control. Is that what you mean?
I'm using the following code to upload multiple documents to the server.
var docFileUploader = new sap.ui.unified.FileUploader({
name : fileUploaderName,
uploadOnChange: false,
uploadUrl: uploadUrlStr,
multiple:true,
additionaldata : nodeObjId ,
fileSizeExceed: function (oEvent) {
var sName = oEvent.getParameter("fileName");
var fSize = oEvent.getParameter("fileSize");
var fLimit = oFileUploader.getMaximumFileSize();
Messenger().post({
message: "File: " + sName + " is of size " + fSize + " MB which exceeds the file size limit of " + fLimit + " MB.",
type: 'error',
showCloseButton: true
});
},
uploadComplete: function (oEvent) {
var sResponse = oEvent.getParameter("response");
console.log(sResponse);
var thisDlg = this.getParent().getParent().getParent().getParent();
console.log(thisDlg);
if (sResponse) {
var m = /^\[(\d\d\d)\]:(.*)$/.exec(sResponse);
if (m[1] == "200") {
uploadSuccess = true;
thisDlg.setBusy(false);
console.log("The document has been uploaded successfully");
setTimeout(function() { Messenger().post("The document has been uploaded successfully");}, 100);
}
else {
thisDlg.setBusy(false);
setTimeout(function() { Messenger().post({
message: 'Oops! Error in document upload. <br>Please try again or contact your administrator.',
type: 'error',
showCloseButton: true
});},100);
}
}
thisDlg.setBusy(false);
console.log("The document has been uploaded successfully");
setTimeout(function() { Messenger().post("The document has been uploaded successfully");}, 100);
thisDlg.close();
thisDlg.destroy();
setTimeout(function() { reloadPage(attrGrpName); }, 100);
}
});
The controller part is as below:
#RequestMapping(value = "doc/upload", method = RequestMethod.POST, consumes = "multipart/form-data")
public #ResponseBody String uploadDoc(#RequestParam("uploadDoc-data") ObjectId nodeId,
#RequestParam(value = "uploadDoc", required = true) MultipartFile[] files, #RequestParam String userId, #RequestParam String passwd) {
if (files != null) {
return service.uploadDoc(nodeId, files[0], userId, passwd);
} else
return "No files found to upload";
}
Even if I use files[0] gives me an ArrayIndexOutofBound 0 Exception. It means the MultipartFile[] is returning an empty array only. I was able to upload one file without multiple attributes. The problem arises if I set the multiple attributes to 'true'. What am I missing? Please help me.