Failed to open stream: HTTP wrapper does not support writeable - codeigniter

when i try to upload files with ajax and CI4 I have this error on the console
jQuery.ajax({
url: "PassagerController/addInformation",
method: "POST",
data : new FormData(this),
dataType:'json',
contentType: false,
cache: false,
processData: false,
the controller:
{
$passager = new PassagerModel();
$id = session()->get('telephone');
$numcni = $this->request->getPost('numcni');
$file = $this->request->getFile('rectocni');
if ($file->isValid() && ! $file->hasMoved()) {
$rectocni = $file->getRandomName();
$file->move(base_url().'/public',$rectocni);
}
then i allready put enctype=multipart/form-data

You are getting the error because you are trying to open a file over HTTP and expect it to be written on a local path. Remove "base_url()" and replace it with a local path.
As you are looking to store the file under the "public" directory, you can update the code to -
if ($file->isValid() && ! $file->hasMoved()) {
$rectocni = $file->getRandomName();
$file->move(ROOTPATH.'public', $rectocni);
}
"ROOTPATH" is a constant that has the path to the project root directory.
It is not good practice to store the uploaded file in the "public" directory, instead, look to place it under a sub directory under "writable".

Related

How to upload pdf files to server from ajax without rails on ruby 2.4

I have a function to submit a file to the server:
function _docs_submit() {
event.preventDefault();
upDOCS_btn.html("Uploading...");
var files = $("#upDOCS").prop('files'),
formData = new FormData();
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type==='application/pdf') {
continue;
}
formData.append('docs[]', file, file.name);
}
$.ajax({
url: "medcon/adddocs",
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function (locks) {
alert('Thank you.\nDocument(s) received.');
},
error: function(e) {
alert("There was an error submitting your documents:\n" + e.responseText);
}
});
}
How should I capture that in ruby and save to the pdf to the server without using rails and on Ruby 2.4?
post 'medcon/adddocs' do |params|
theFile = params[:data] # need help here
#save file to server - need help here especially
end
I can use gems as long as they match with Ruby 2.4. Thanks.
To access the contents of uploaded file you use file_param[:tmpfile] and you can also access original filename under file_param[:filename] (not sure if you want to reuse it. Armed with that knowledge, you should be able to handle your upload with something like that (not tested, from memory):
post 'medcon/adddocs' do |params|
files = param[:data][:docs] # or maybe string keys, I'm not sure
files.each do |file|
name = file[:filename]
contents = file[:tmpfile].read
File.open(File.join('/some/path', filename), 'wb') { |f| f.write(contents) }
end
end
To access the param values by key, use tic marks. Here's the solution I went with, which includes a method for creating a file directory where it doesn't already exist. To write the file use file.open and wb to write the file in binary mode.
require 'fileutils'
def create_folder(path)
unless File.directory?(path)
FileUtils.mkdir_p(path)
end
end
post 'medcon/adddocs' do |params, me|
params = params['body']
filename = params['data']['filename']
fid = params['fid'].to_s
file = Base64.decode64(params['data']['file_base64'])
folder = "../data/medcon/fid#{fid}"
create_folder folder # send folder path to create folder method
File.open("#{folder}/#{filename}", 'wb') do |f|
f.write(file)
end
end

docompress-zip in Node WebKit app cannot unzip downloaded file, downloaded file "corrupt" according to WinRAR

I'm attempting to write an automated installer for a *.exe file. I am using node-webkit, my unzipper is decompress-zip. I am downloading the installer via AJAX:
$.ajax({
type: "GET",
url: 'https://mywebste.com/SyncCtrl.zip',
contentType: "application/zip;",
success: function (dat) {
console.log(dat)
fs.writeFile("./SyncCtrl.zip", dat, function () {
console.log(dat)
})
},
error: function (err) {
console.log(err)
fs.writeFile("./SyncCtrl.zip", err.responseText, function () {
})
}
})
The .zip is written through the err.responseText content. I know this isn't best practice, but I haven't been able to get it into the success callback, even though the response code is 200. This is for another question though.
After I write the .zip file to disk, I wait for an authentication request, then unzip it in the success callback:
var unzip = new dc("./SyncCtrl.zip")
unzip.on('error', function (err) {
console.log("Something went terribly wrong.")
console.log(err)
})
unzip.on('extract', function (log) {
console.log("Finished!")
console.log(log)
})
unzip.on('progress', function (i, c) { //index, count (irrelevant for single file)
console.log("Extraction progress.")
})
unzip.extract({
path: "./SyncCtrl"
})
This is nearly copy/pasted directly from the decompress-zip github page. This fails, in the error handler it prints:
Error {message: "File entry unexpectedly large: 80606 (max: 4096)"}
I assume this limit is in MB? This is very confusing as in both locations the file size on disk is 1.7MB for the file I'm trying to extract. Any help is greatly appreciated.
The best way to accomplish this is to interpret the static file as a stream.
Simply using the static file on the server, this is my working node-webkit code:
var file = fs.createWriteStream("./MOCSyncCtrl.zip");
var request = https.get("https://moc.maps-adr.com/MOCSyncCtrl.zip", function (response) {
response.pipe(file);
});

rename file with django-ajax-uploader

I am using https://github.com/skoczen/django-ajax-uploader to upload a file in django. It works but I would like to rename the uploaded file during the process. I want to add a timestamp so I am sure it has a unique name.
How to do that?
I finally ended up using jQuery-File-Upload. It allows to define the path of the file inside the view.Example:
urls.py
url(r'^upload_question_photo/$', UploadQuestionPhoto.as_view(), name="upload_question_photo"),
index.html
var input=$(this).find("input");
var formData = new FormData();
formData.append('photo', input[0].files[0]);
formData.append('question', input.attr("name"));
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
input.fileupload(
{
dataType: 'json',
url: "{% url 'campaigns:upload_question_photo' %}",
formData: formData,
//the file has been successfully uploaded
done: function (e, data)
{
response=data.result;
window.console&&console.log("Successfully uploaded!");
window.console&&console.log(response.path);
}.bind(this),
processfail: function (e, data)
{
window.console&&console.log('Upload has failed');
}.bind(this)
});
views.py
class UploadQuestionPhoto(View):
u"""Uploads photos with ajax
Based on the code #https://github.com/miki725/Django-jQuery-File-Uploader-Integration-demo/blob/master/upload/views.py
"""
def post(self, request, *args, **kwargs):
print "UploadQuestionPhoto post"
response={}
question=str(request.POST["question"])
#path where the file is going to be stored
path="/question/" + question + "/"
photo_path=settings.MEDIA_ROOT + path
# if 'f' query parameter is not specified -> file is being uploaded
if not ("f" in request.GET.keys()):
print "file upload"
# make sure some files have been uploaded
if request.FILES:
# get the uploaded file
photo_file = request.FILES["question_field_" + question]
name_with_timestamp=str(time.time()) + "_" + photo_file.name
# create directory if not exists already
if not os.path.exists(photo_path):
os.makedirs(photo_path)
# add timestamp to the file name to avoid conflicts of files with the same name
filename = os.path.join(photo_path, name_with_timestamp)
# open the file handler with write binary mode
destination = open(filename, "wb+")
# save file data with the chunk method in case the file is too big (save memory)
for chunk in photo_file.chunks():
destination.write(chunk)
destination.close()
#response sent back to ajax once the file has been successfuly uploaded
response['status']='success'
response["path"]=photo_path+name_with_timestamp
# file has to be deleted (TODO: NOT TESTED)
else:
# get the file path by getting it from the query (e.g. '?f=filename.here')
filepath = os.path.join(photo_path, request.GET["f"])
os.remove(filepath)
# generate true json result (if true is not returned, the file will not be removed from the upload queue)
response = True
# return the result data (json)
return HttpResponse(json.dumps(response), content_type="application/json")
VoilĂ  ! Hope it helps.

Unable to get value of the property 'content': object is null or undefined

I get this error every time i compile my PhoneGap 2.9.0 project. I copied "www" folder into my Microsoft Visual Studio 2010 Codrova Project because iw anted to test the program on WP 7(I've already tested it on Android and iOS emulators and devices).
Error:["Unable to get value of the property 'content': object is null or undefined file:x-wmapp1:\/app\/www\/index.html Line:1","DebugConsole380383071"]
As far as i've found out, this bug is fixed only if i delete cordova.js include in my index.html file. I'm hoping that fixing this bag will solve the problem of file downloading in my program, because it's not working in WP 7 now. Here is the function for file downloading:
function fileDownload(fileName, finalName) {
window.requestFileSystem(
LocalFileSystem.PERSISTENT, 0,
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getFile(
"dummy.html", {create: true, exclusive: false},
function gotFileEntry(fileEntry){
var sPath = fileEntry.fullPath.replace("dummy.html","") + "Appname/Cachefolded";
var fileTransfer = new FileTransfer();
fileEntry.remove();
fileTransfer.download(
finalName,
sPath + finalName,
function(theFile) {},
function(error) {}
);
},
null);
},
null
);
};
In addition, i'm using few PhoneGap API's:
* Device
* Connection
* FileSystem
* LocalStorage
Data is downloaded via Ajax like this:
$.ajax({
url: base + "user.php?imei=" + imei,
type: 'POST',
dataType:"json",
cache: false,
success: function(data) {
fileDownload(data.img, "avatar.jpg");
}
});
I'll publish all nessesary code if you are interested in a specific part. Don't wanna post it here to keep my question readable. Thanks for any help in advance.
P.S. Line 1 of the code is:
<!DOCTYPE html>

Passing the uploaded file path to controller action using uploadify

I'm using uploadify in my MVC3 project. It works fine to upload multiple files and saving to folders as well.
How to pass the path of the uploaded file to controller action ? -- I need to pass it to the ExtractingZip action of my controller.
To extract the contents of the .zip file, I'm using DotNetZip Library.
Here is what i've tried so far.
$('#file_upload').uploadify({
'checkExisting': 'Content/uploadify/check-exists.php',
'swf': '/Content/uploadify/uploadify.swf',
'uploader': '/Home/Index',
'auto': false,
'buttonText': 'Browse',
'fileTypeExts': '*.jpg;*.jpeg;*.png;*.gif;*.zip',
'removeCompleted': false,
'onSelect': function (file) {
if (file.type == ".zip") {
debugger;
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("ExtractingZip", "Home")',
data: ({ fileName: file.name}), // I dont see a file.path to pass it to controller
success: function (result) {
alert('Success');
},
error: function (result) {
alert('error');
}
});
}
}
});
Here is my controller action:
[HttpPost]
public ActionResult ExtractingZip(string fileName,string filePath, HttpPostedFileBase fileData)
{
string zipToUnpack = #"C:\Users\Public\Pictures\Sample Pictures\images.zip";// I'm unable to get the filePath so i'm using the path.
string unpackDirectory = System.IO.Path.GetTempPath();
using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
{
// here, we extract every entry, but we could extract conditionally
// based on entry name, size, date, checkbox status, etc.
var collections = zip1.SelectEntries("name=*.jpg;*.jpeg;*.png;*.gif;");
foreach (var item in collections)
{
item.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
}
}
return Json(true);
}
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> fileData)
{
foreach (var file in fileData)
{
if (file.ContentLength > 0)
{
string currpath;
currpath = Path.Combine(Server.MapPath("~/Images/User3"), file.FileName);
//save to a physical location
file.SaveAs(currpath);
}
}
}
You don't need to pass the zip's filepath when it's uploaded. The filepath would be from the clients machine right? Your application on your server has no knowledge or access to the clients file system.
The good news is you don't need it. You already have the contents of your file in memory. I have never used donetzip but some quick googling reveals that you can read zips directly from a stream.
Check out these links:
Cannot read zip file from HttpInputStream using DotNetZip 1.9
Extracting zip from stream with DotNetZip
So using those posts as a base to go off of... It looks like you should be able to change your code like so:
string zipToUnpack = #"C:\Users\Public\Pictures\Sample Pictures\images.zip";// I'm unable to get the filePath so i'm using the path.
string unpackDirectory = System.IO.Path.GetTempPath();
using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
{
....
Changes to...
string unpackDirectory = System.IO.Path.GetTempPath();
using (ZipFile zip1 = ZipFile.Read(fileData.InputStream))
{
....
Let me know if that helps.
First of, due to security reasons you have no access directly to clients machine. While a user uploads some files, web browsers make one or tow (usually 1, according to RFC) stream and server-side script reads that stream, so do not waste your time to get files directly from user's local machine's filepath.
To extract archives (s.a: Zip, Rar) I highly recommend you to use SevenZipSharp. It works really good and easy with Streams and also many compression formats.
As they documentation you can extract stream like this:
using (MemoryStream msin = new MemoryStream(fileData.InputStream))
{ ... }

Resources