How to Remove Physical Files in kendoUpload - javascript

I am using Kendo UI uploader. When I upload the files using kendoUpload, actually I rename the files using Guid.NewGuid() in server side. The problem is that, when I want to remove the files, the original file name is sent to remove handler in server side instead of guidName. How can I solve this issue?
My remove handler in server side is as follows:
[HttpPost]
public ActionResult RemoveTemp(string[] fileNames)
{
List<string> removedFiles = new List<string>();
string tempPath = Server.MapPath("~/temp/");
if (fileNames != null)
{
foreach (var fullName in fileNames)
{
File.Delete(tempPath + fullName);
removedFiles.Add(fullName);
}
}
return Json(removedFiles.ToArray());
}
My remove event in client side is as follows:
remove: function (e) {
var fileToRemove = e.files[0].name;
for (var i = 0; i < vm[item].length; i++) {
if (vm[item][i].originalName == fileToRemove) {
vm[item].splice(i, 1);
break;
}
}
// I don't know how to send guidNames here using e.data
}

You need to include the name of the saved files in the upload response, and at the client, set the name of the e.files accordingly.
Sample upload action:
[HttpPost]
public ActionResult UploadFiles()
{
// Note: We use Request.Files instead of a parameter input, to be independent of the name of the Kendo upload component
var count = Request.Files.Count;
if (count == 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var result = new List<UploadedFile>(count);
for (var i = 0; i < count; i++)
{
HttpPostedFileBase file = Request.Files[i];
if (file == null || (file.ContentLength == 0 && string.IsNullOrEmpty(file.FileName)))
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
// Some browsers send file names with full path. We are only interested in the file name.
var fileName = Path.GetFileName(file.FileName);
var tempKey = _svcUpload.SaveTempFile(file.InputStream, fileName);
result.Add(new UploadedFile
{
TempKey = tempKey,
Name = fileName,
Extension = Path.GetExtension(file.FileName),
Size = file.ContentLength
});
}
return Json(result);
}
_svcUpload.SaveTempFile() saves an uploaded file and returns its temp key (which can be the GUID of your renamed file). We include the temp key, along with other file info, in the response.
Here is the client-side upload-success handler:
function fileUploadSuccess(e) {
if (e.operation === 'upload') {
for (var i = 0; i < e.response.length; i++) {
var tempKey = e.response[i].TempKey;
e.files[i].name = tempKey;
}
}
}

Related

.NET Framework MVC Large file upload

I am trying to upload large binary files from a web client to a .NET 4.6.1 Framework MVC API. These files could range anywhere from 5GB to 20GB.
I have tried splitting the file into chunks to upload each chunk and merge the results at the end, but the merged file is always corrupted. If I work with small files and don't split, the binary will work correctly. However, when I split and merge the file is "corrupted". It won't load or behave as expected.
I have looked all over and haven't seen a proper solution to this so i'm hoping someone can help me here.
I followed this https://forums.asp.net/t/1742612.aspx?How+to+upload+a+big+file+in+Mvc, but I can't get it to work and the corrected solution was never posted. I am keeping track of the order of files before merging on the server.
Javascript (Call to uploadData is made to initiate)
function uploadComplete(file) {
var formData = new FormData();
formData.append('fileName', file.name);
formData.append('completed', true);
var xhr3 = new XMLHttpRequest();
xhr3.open("POST", "api/CompleteUpload", true); //combine the chunks together
xhr3.send(formData);
return;
}
function uploadData(item) {
var blob = item.zipFile;
var BYTES_PER_CHUNK = 750000000; // sample chunk sizes.
var SIZE = blob.size;
//upload content
var start = 0;
var end = BYTES_PER_CHUNK;
var completed = 0;
var count = SIZE % BYTES_PER_CHUNK == 0 ? SIZE / BYTES_PER_CHUNK : Math.floor(SIZE / BYTES_PER_CHUNK) + 1;
while (start < SIZE) {
var chunk = blob.slice(start, end);
var xhr = new XMLHttpRequest();
xhr.onload = function () {
completed = completed + 1;
if (completed === count) {
uploadComplete(item.zipFile);
}
};
xhr.open("POST", "/api/MultiUpload", true);
xhr.setRequestHeader("contentType", false);
xhr.setRequestHeader("processData", false);
xhr.send(chunk);
start = end;
end = start + BYTES_PER_CHUNK;
}
}
Server Controller
//global vars
public static List<string> myList = new List<string>();
[HttpPost]
[Route("CompleteUpload")]
public string CompleteUpload()
{
var request = HttpContext.Current.Request;
//verify all parameters were defined
var form = request.Form;
string fileName;
bool completed;
if (!string.IsNullOrEmpty(request.Form["fileName"]) &&
!string.IsNullOrEmpty(request.Form["completed"]))
{
fileName = request.Form["fileName"];
completed = bool.Parse(request.Form["completed"]);
}
else
{
return "Invalid upload request";
}
if (completed)
{
string path = HttpContext.Current.Server.MapPath("~/Data/uploads/Tamp");
string newpath = Path.Combine(path, fileName);
string[] filePaths = Directory.GetFiles(path);
foreach (string item in myList)
{
MergeFiles(newpath, item);
}
}
//Remove all items from list after request is done
myList.Clear();
return "success";
}
private static void MergeFiles(string file1, string file2)
{
FileStream fs1 = null;
FileStream fs2 = null;
try
{
fs1 = System.IO.File.Open(file1, FileMode.Append);
fs2 = System.IO.File.Open(file2, FileMode.Open);
byte[] fs2Content = new byte[fs2.Length];
fs2.Read(fs2Content, 0, (int)fs2.Length);
fs1.Write(fs2Content, 0, (int)fs2.Length);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + " : " + ex.StackTrace + " " + file2);
}
finally
{
if(fs1 != null) fs1.Close();
if (fs2 != null)
{
fs2.Close();
System.IO.File.Delete(file2);
}
}
}
[HttpPost]
[Route("MultiUpload")]
public string MultiUpload()
{
try
{
var request = HttpContext.Current.Request;
var chunks = request.InputStream;
string path = HttpContext.Current.Server.MapPath("~/Data/uploads/Tamp");
string fileName = Path.GetTempFileName();
string newpath = Path.Combine(path, fileName);
myList.Add(newpath);
using (System.IO.FileStream fs = System.IO.File.Create(newpath))
{
byte[] bytes = new byte[77570];
int bytesRead;
while ((bytesRead = request.InputStream.Read(bytes, 0, bytes.Length)) > 0)
{
fs.Write(bytes, 0, bytesRead);
}
}
return "test";
}
catch (Exception exception)
{
return exception.Message;
}
}

Uploading files via axios to WebApi

I'm getting this error when trying to upload a file to webapi
Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFile'
javascript:
UploadReceivingIssueImages(e) {
if (!e.target.files || e.target.files.length === 0)
return;
let formData = new FormData();
for (var i = 0; i < e.target.files.length; i++) {
formData.append('file', e.target.files[i]);
}
var vm = this;
axios.post('../api/receiving/UploadDocReceivingIssueImages?headerId=' + this.SelectedSubIdIdObj.HeaderId,
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function () {
vm.getDocReceivingIssueImages();
console.log('SUCCESS!!');
}, function (er) {
alert("Couldn't upload images")
});
}
WebApi Code
[HttpPost]
public bool UploadDocReceivingIssueImages([FromUri] int headerId)
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count < 1)
{
var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent("No File Uploaded"),
ReasonPhrase = "No File Uploaded"
};
throw new HttpResponseException(resp);
}
var dirPath = #"\\dirPath";
foreach (var f in httpRequest.Files)
{
var pf = (System.Web.HttpPostedFile)f;
pf.SaveAs(dirPath + Guid.NewGuid().ToString() + pf.FileName);
}
return true;
}
the error happens at
var pf = (System.Web.HttpPostedFile)f;
the f object is a string with value 'file'... WHY?!?!
any help would be appreciated.
Because when you enumerate over HttpRequest.PostedFiles you're enumerating over its keys (the names, which are all 'file' based on your JS), not the files:
foreach (var key in httpRequest.Files)
{
var pf = httpRequest.Files[key]; // implicit cast to HttpPostedFile
pf.SaveAs(dirPath + Guid.NewGuid().ToString() + pf.FileName);
}
EDIT TO ADD:
With that said, you'll need to update your JS to use unique names in FormData or else you'll only be able to read one file out of your HttpContext's HttpFileCollection:
for (var i = 0; i < e.target.files.length; i++) {
formData.append('file' + i, e.target.files[i]);
}
See HttpFileCollection on MSDN

How do I upload file on an aspx page without using webforms?

I have an aspx page which already has a code for uploading file using "asp:FileUpload" and webform. On a different section of page, I want to add the functionality for a user to upload file. But i do not want to use webforms or "asp:fileupload".
So, I created an HTML file that i inject as an iframe inside a div tag on the aspx.
<div id="iUploadDoc" style="height:50px;">
<iframe name='FileUpload' id='FileUpload' class='iUploadFrame' width='100%' frameborder='0' border='0'src='DocUpload.htm'></iframe></div>
I set the EnablePageMethods to true.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
And inside the HTML I made a form and with input type file.
<form method="POST" action="DocDetail.aspx.cs" id="docUpload" enctype="multipart/form-data">
<div>
<label for="fileUpload" class="inputLabel">Upload File</label>
<input type="file" id="fileUpload" name="files"/>
</div>
</form>
<div id="progUpload" style="display: none;">
<p class="uploadBox">Uploading...</p>
</div>
<span id= "selectedFile" style="display: none;"></span><span id="fileName" style="display: none;"></span>
Now, I dont know what to put in the "action" param of form.
First on the iframe, below is the script i wrote:
window.onload = load;
function uploadDocFile() {
var prog = document.getElementById("progUpload");
prog.style.cssText = 'display: block;';
var x = document.getElementById("fileUpload");
var txt = "";
var filePath = "";
var fileName = "";
if (x.value == "") {
txt += "Select a file.";
document.getElementById("selectedFile").innerHTML = txt;
} else {
filePath = x.value;
fileName = filePath.replace(/^.*[\\\/]/, '');
txt += "<br>Selected file: ";
document.getElementById("selectedFile").innerHTML = txt;
document.getElementById("fileName").innerHTML = fileName;
}
var formInfo = document.getElementById("docUpload");
document.getElementById("docUpload").style.display = "none";
window.parent.getFormData(formInfo, x ,x.value, fileName);
}
function load() {
var e = document.getElementById("fileUpload");
//var formInfo = document.getElementById("docUpload");
//fakeClick();
e.onchange = function () {
uploadDocFile();
}
}
Then on the parent page, below is the script i wrote.
DocUpload.prototype.uploadFileDoc= function (formInfo, uploadedFile, fileInfo, lastModifiedDate, name, extension, size, type) {
//blacklitsType is an array of types of file (similarly for blacklistExt) that should not be allowed to upload
if (indexOf.call(blackListType, type) < 0 && indexOf.call(blackListExt, extension) < 0) {
var idParams = { OiD: ordId, pID: pId, QID: qId }
var files = uploadedFile.files;
var fileEntries = [];
for (j = 0, len1 = files.length; j < len1; j++) {
file = files[j];
if (file.getAsEntry) {
entry = file.getAsEntry();
} else if (file.webkitGetAsEntry) {
entry = file.webkitGetAsEntry();
}
if (entry) {
isFyl = entry.isFile;
if (!isFyl) {
alert("You can not upload a folder. Uploading files (if present).");
} else {
fileItem = file.getAsFile();
fileEntries.push(fileItem);
}
} else if (!file.type && file.size % 4096 === 0) {
alert("You can not upload a folder. Uploading files (if present).");
} else {
fileEntries.push(file);
}
}
PageMethods.UploadDocument(fileEntries[0], idParams, function (res) {
if (res == true) {
alert("File uploaded successfully.");
} else {
alert("File upload failed.");
}
}, function (err) {
alert("ERROR: " + err._message);
});
} else {
window.alert('You cannot upload incorrect file types.');
}
return;
};
DocUpload.prototype.getFormData = function (formInfo, uploadedFile, fileInfo, nameInfo) {
var currDate, extension, lastModifiedDate, name, nameArr, size, type;
currDate = new Date();
lastModifiedDate = currDate;
type = '';
size = 512;
name = nameInfo;
nameArr = name.split(".");
extension = nameArr[nameArr.length - 1];
DocUpload.prototype.uploadFileDoc(formInfo, uploadedFile, fileInfo, lastModifiedDate, name, extension, size, type);
};
window.getFormData = DocUpload.prototype.getFormData;
The transfer of attributes of form from iframe to parent page work just fine. But how should i post it as file using PageMethod. Below is the page method in my code behind:
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = false)]
public static bool UploadDocument(HttpPostedFileBase uploadedFile,IdParams idParams) {
bool err = false;
try{
//code
err= true;}
catch(Exception ex){err = false;}
return err;
}
No matter how much tried, either I keep getting error regarding HTTPPostedFileBase or Serialization of child not allowed.Below are only some of the errors i keep getting (not at the same time):
No parameterless constructor System.Web.HttpPostedFileBase aspx, OR
The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter
What should i do?

Jquery progress bar while uploading record into database in java

I have thousands of record which are stored in a excel sheet and I need to upload those records into database, And currently I am using Spring controller class for upload, And inside my class I use simple BufferedOutputStream and FileReader classes, So my requirement is I need to show a Jquery progress-bar including percentages while uploading my data into database.
Link here.
My sample code.
String rootPath = request.getSession().getServletContext().getRealPath("/");
File dir = new File(rootPath + File.separator + "uploadedfile");
if (!dir.exists()) {
dir.mkdirs();
}
File serverFile = new File(dir.getAbsolutePath() + File.separator + form.getEmpFile().getOriginalFilename());
try {
try (InputStream is = form.getEmpFile().getInputStream();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
int i;
//write file to server
while ((i = is.read()) != -1) {
stream.write(i);
}
stream.flush();
}
}
catch (IOException e) {
model.addAttribute("msg", "failed to process file because : " + e.getMessage());
}
String[] nextLine;
try (FileReader fileReader = new FileReader(serverFile); CSVReader reader = new CSVReader(fileReader, ';', '\'', 1);) {
while ((nextLine = reader.readNext()) != null) {
for (int i = 0; i < nextLine.length; i++) {
nextLine[i] = nextLine[i].trim();
if (!nextLine[i].equals("")) {
String[] data = nextLine[i].split(",");
Maybe this can help:
1- Controller side :
public class ExtractController {
********
// I created a global variable here
int percentage = 0;
Workbook workbook;
#RequestMapping(value ="/uploadExcel", method = RequestMethod.POST)
public #ResponseBody String uploadExcel(Model model, #RequestParam("excelfile") MultipartFile excelfile,
HttpServletResponse response) {
**********
try {
int i = 0;
*********
while (i <= worksheet.getLastRowNum()) {
percentage = Math.round(((i * 100) / worksheet.getLastRowNum()));
Row row = worksheet.getRow(i++);
}
*********
}catch (Exception e) {
e.printStackTrace();
}
return "extract";
}
#RequestMapping(value = "/getpercent", method = RequestMethod.GET)
public #ResponseBody String getPerc(#RequestParam("param") String param) {
************
// you return the value of the global variable when the action is called
return percrentage;
}
}
1- JavaScript side :
$.ajax({
url : 'uploadExcel',
type : 'POST',
data : new FormData(this),
beforeSend : function() {
$('#valid').attr("disabled", true);
// I call my loop function
loop();
},
success : function(data) {
$('#valid').attr("disabled", false);
}
});
function loop() {
$.ajax({
url : 'getpercent',
type : 'GET',
success : function(response) {
count = response;
// this function updates my progress bar with the new value
change(count);
*********
}
});
var time = 2000;
if(count < 100){
setTimeout(loop, time);
}
}
;

allow file with a specific filename and extension to be uploaded

I am new to javascript and I need to check that the filename has to be uploaded only if it has the specific name and a specific extension. How do i do that? For example: I can upload file only if it has filename: can_to_do and extension: pdf else it will send out an alert asking us to change the filename
Suppose i need to upload jrxml file extension. so the validation goes something like that. say file name someFile.jrxml
var fileVal = $('#fileId').val();
if (fileVal != null && fileVal != '')
{
var ext = fileVal.split('.').pop().toLowerCase();
if ($.inArray(ext, ['jrxml']) == -1) {
jAlert('Not a valid file');
isOk = false;
}
}
I found the solution for this question I posted that is to be able to upload only if the file has a particular filename and extension. Here, for example: "ReleaseNotes.txt". It is in Javascript:
function uploadFile()
{
var fileElement = document.getElementById("fileToUpload");
var x = document.getElementById("fileToUpload");
var txt = "";
if ('files' in x) {
if (x.files.length != 0) {
for (var i = 0; i < x.files.length; i++) {
var file = x.files[i];
if ('name' in file) {
if (file.name == "ReleaseNotes.txt")
{
alert("pass");
}
else{
alert("fail");
}
}

Categories