Upload file having special character in name using Angular ngf-select - javascript

I am working on Angular2 application with spring boot in back-end. In application there is feature to upload file on server. The code to upload file working fine.
I am using ngf-select to choose file. It works well when file name is without special characters.
<input type="file" name="file" ng-model="obj.fileModel" ngf-select accept="file_extension">
The problem occurs when I choose file having special character like my name neelam shrma ## !! %%% ggg %.json
Upload js code is :
var formData = new FormData();
formData.append("fileObj", obj.fileModel);
UploadFile.save(formData, onUploadSuccess, onUploadError);
As file obj.fileModel having File object with special character name, so it do not call resource method to upload file
Also I have tried by updating the file name withe encoding, but as file object is read-only, so won't allowing me to change the name, also created new file object with encoded file name, but didn't worked.
Resource Method :
public boolean uploadMyFile(MultipartFile mpfile) throws IOException {
...
....
File file = new File(myFolder + File.separator + file.getOriginalFilename());
mpfile.transferTo(file);
......
......
}
So the file having special character not calling my resource method : uploadMyFile(..) and throwing 500 server error.
How to resolve the issue of uploading file having special character using angularJs ngf-select?

Add a filter as below
.filter('decodeURL', function () {
return function (text) {
if (text) {
return window.encodeURIComponent(text);
}
}
});
and below html
<img src="{{itemDetails.LargeImageName | decodeURL}}" />

Related

$_FILES['file'] turn null while using filepond

This is the ordinary input file with HTML in the form with method POST
<input type="file" name="file" accept="image/png, image/jpeg">
then Ill get that file input with this function written in PHP
function Upload() {
$namefile = $_FILES['file']['name'];
$error = $_FILES['file']['error'];
$tmpName = $_FILES['file']['tmp_name'];
move_uploaded_file($tmpName, 'upload/'.$namefile);
return $namafile;
}
Ya that's success. The file move to folder 'upload'.
But I want to try styling my form input with Filepond.
<input class="filepond" type="file" name="file" accept="image/png, image/jpeg">
With this js
const inputElement = document.querySelector(".filepond");
FilePond.registerPlugin(
FilePondPluginFileValidateType,
FilePondPluginFileValidateSize
)
FilePond.create(inputElement, {
labelIdle: 'Upload Photo<span class="filepond--label-action">Browse</span>',
maxFiles: '1',
maxFileSize: '5MB',
labelMaxFileSizeExceeded: 'Too big bro.',
labelMaxFileSize: 'max {filesize}',
labelFileTypeNotAllowed: 'Meh dont up that type',
fileValidateTypeLabelExpectedTypes: 'just {allTypes}'
})
But when I try to get the file with the same method as before, $_FILES['file'] will just turn null.
Instead of styling your input, filepond may be creating a proxy element with a different name.
Try var_dump($_FILES) and see if it has been named something else.
As browsers cannot update the file input field value the file is stored in a separate field.
This means you either have to encode the file as a base64 string and then upload that with the form submit (and then decode on the server).
Or you have to upload the file asynchronously by setting the FilePond server property to a page on the server that handles the upload.
A third alternative is setting the storeAsFile property to true, FilePond will now update the file input field, but this only works if the browser supports the DataTransfer constructor

Replace "C:\fakepath\" to "\\server\folder\"

I use javascript code to take the file path and paste it into the text input. I am wondering how to make it substitute a predefined server path in front of the file name instead of the path "C:\fakepath", e.g: "\server\dir\data".
$('input[type="file"]').change(function(){
$('input[type="text"]').val( $(this).val());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" enctype="multipart/form-data">
<input type="file" onchange="this.form.filename.value = this.value">
<input type="text" name="filename">
</form>
The String object has a number of methods that you could use for this. For example using substr:
<script>
$('input[type="file"]').change(function(){
$('input[type="text"]').val( '\\server\\dir\\data'+$(this).val().substr(11));
})
</script>
Some browsers have a security feature that prevents JavaScript from knowing your file's local full path and because of which you are getting fakepath in the file path url. This security feature is added so that the server won't able to know the filesystem of your machine.
In case you you want to remove the fakepath from path then what you can do is to -
$('input[type="text"]').val( '\'+$(this).val());
This will show the the path as \file_name.extension
of what you wrote i guess that you are trying to do file upload by sending the file data from files object to the server by ajax but you cannot send this path or replace it because it's a random path generated when the server received the file to be uploaded but you can easily use FormData object to send the file to the server then you can handle it from your server
Here's an example
var photo = document.getElementById("photo")
photo.addEventListener("change",function(event) {
var form_data = new FormData();
form_data.append("file",event.target.files[0]);
$.ajax({
url: './phpScripts/up.php',
type: "post",
processData: false,
contentType: false,
data: form_data
}).done(function(e) {
//Code here
})
})
the last point if you wants to get the file path just test the event in the console console.log(event) then search for files object when you can find the file path and access it

Kendo UI multiple files upload issue

I am using a Kendo File Upload control to upload multiple files. Only few of the files are getting uploaded (especially first and last) or some random ones. Is there any solution for this ?
Index.cshtml :
<input name="files" id="files" type="file" multiple="multiple" />
JS File :
$("#files").kendoUpload
({
async: {
saveUrl: "/Controller/GetUserUploadedFiles",
removeUrl: "/Controller/Remove",
autoUpload: false,
allowmultiple: true
},
select: function (e) {
onSelect(e);
},
success: function (e) {
},
error: function (e) {
}
});
//Controller Method
[HttpPost]
public void GetUserUploadedFiles(IEnumerable<HttpPostedFileBase> files)
{
//Custom logic here
}
Also, it would be great if i can get all the files as Enumerable in one controller method call rather than having it called multiple times for multiple files.
Is there anything i am missing or doing wrong ?
Thanks,
Srini
This code will upload all the files that were selected in Kendo Upload, and then run code on each.
[HttpPost]
public void GetUserUploadedFiles()
{
Request.Content.LoadIntoBufferAsync().Wait();
var result = Task.Factory
.StartNew(() => Request.Content.ReadAsMultipartAsync().Result,
CancellationToken.None,
TaskCreationOptions.LongRunning,
TaskScheduler.Default).Result;
var contents = result.Contents;
HttpContent httpContent = contents.First();
Stream file = httpContent.ReadAsStreamAsync().Result;
if (file.CanRead)
{
// Code that will be executed on each file
}
}
You can get the filename by using:
string filename = httpContent.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
You can get the uploaded file media type by using:
string uploadedFileMediaType = httpContent.Headers.ContentType.MediaType;
IIRC, the kendo batch option will only upload the files as a collection if selected at the same time (browse, then select more than one file). Once you select additional file(s) they will be sent in another request. The only way you can force the files to be posted during the same request is to use the synchronous mode rather than async. Good luck.

how to export csv file with filename

I want to export the exist data into csv file. I try to use this code:
var uriContent = "data:text/csv;charset=utf-8," + encodeURIComponent(data);
var myWindow = window.open(uriContent);
myWindow.focus();
it works but I can design filename. I can only get the dialog with name like "MVeAnkW8.csv.part" which I don't know where the name come from.
How can I assign filename in the first dialog? Thanks in advance.
update:
I am now using rails. Actually I have a method in server side names export_to_csv. In end of this method, I use code like that:
send_data(csv_string,
:type => 'text/csv; charset=utf-8;',
:filename => "myfile.csv")
It works and I can specify the file name.
For now, I want to use ajax to get more csv files(that is the reason why I want to use javascript, because a normal http request can only get one file to be downloaded).
I use js code like that:
$.post("export_to_csv",
function(data) {
var uriContent = "data:text/csv;charset=utf-8," + encodeURIComponent(data);
var myWindow = window.open(uriContent);
myWindow.focus();});
It get the data from server side and I try to transfer it into csv. I can get a file but can't specify the file name.
As I know, you can specify the filename only in chrome 14+.
Take a look at this question: Is there any way to specify a suggested filename when using data: URI?
Update!
If you want to download multiple csv files "at once", you can zip them together, or save each file on the server separately (each file now has a url that points to it - if you place them inside the 'www' folder).
Then send the file names and their path/url to the client via ajax (use a json encoded list for example).
In the ajax callback function: take the list of the files and open each file-url in a separate popup.

Selecting file using javascript then upload

I appended blob data (that I converted from urldata) to a form. The code I use is as follows:
var blob = dataURItoBlob(row.pict);
var fd = new FormData(document.forms[0]);
fd.append("uploadFile", blob);
I intend to set the blob as the selected file for an input with type file:
<input type="file" name="uploadFile" id="btn_pic" />
But when I click the submit button, server does not recognize the file I want to upload. The server reads the parameter as null (I am using ASP .NET MVC3). I use The code below in the server-side:
public ActionResult Create(Discussion d, HttpPostedFileBase uploadFile)
{
....
}
is there any way I can do to set the selected file using javascript?

Categories

Resources