How to get multiple selected file in grails? - mysql

I am trying to get multiple selected files and save into mysql
GSP CODE :
<input type="file" name="file_attachemnt" id="file_attachemnt" multiple/>
Controller Code For multiple file get
def all = request.getFileNames()
all.each {name ->
def file = request.getFile(name)
def CommonsMultipartFile uploadedFile =file
def fileName = uploadedFile.originalFilename
println "file name "+fileName;
def fileExtent=FilenameUtils.getExtension(fileName);
}
But in controller side only one file i get.. even if i selected e.g 3 files

Give this a try. Not sure but I don't think much has changed since the 1.3.x days and this works there.
request.getMultiFileMap().file_attachemnt.each {
println it.originalFilename
}

Try this code
params.list("file_attachemnt").each{
// your code here
}

Related

Import csv file in drf

I'm trying to create a view to import a csv using drf and django-import-export.
My example (I'm doing baby steps and debugging to learn):
class ImportMyExampleView(APIView):
parser_classes = (FileUploadParser, )
def post(self, request, filename, format=None):
person_resource = PersonResource()
dataset = Dataset()
new_persons = request.data['file']
imported_data = dataset.load(new_persons.read())
return Response("Ok - Babysteps")
But I get this error (using postman):
Tablib has no format 'None' or it is not registered.
Changing to imported_data = Dataset().load(new_persons.read().decode(), format='csv', headers=False) I get this new error:
InvalidDimensions at /v1/myupload/test_import.csv
No exception message supplied
Does anyone have any tips or can indicate a reference? I'm following this site, but I'm having to "translate" to drf.
Starting with baby steps is a great idea. I would suggest get a standalone script working first so that you can check the file can be read and imported.
If you can set breakpoints and step into the django-import-export source, this will save you a lot of time in understanding what's going on.
A sample test function (based on the example app):
def test_import():
with open('./books-sample.csv', 'r') as fh:
dataset = Dataset().load(fh)
book_resource = BookResource()
result = book_resource.import_data(dataset, raise_errors=True)
print(result.totals)
You can adapt this so that you import your own data. Once this works OK then you can integrate it with your post() function.
I recommend getting the example app running because it will demonstrate how imports work.
InvalidDimensions means that the dataset you're trying to load doesn't match the format expected by Dataset. Try removing the headers=False arg or explicitly declare the headers (headers=['h1', 'h2', 'h3'] - swap in the correct names for your headers).

Create Button on existing model to download CSV data

I have a function that generates a CSV report for survey.surveys to my employer's liking and I need a way to download that data. The issue I'm having is to get a button on the page to actually download the data, I've tried adding a controller but when I go to it, it says 404.
I'm using Odoo 13
Here's the controller I tried, but when i go to it, it returns a 404. Yes i checked my __init__.py for both my module and controllers folder
class MyExport(http.Controller):
#http.route(['/my_module/export/certs'], type='http', auth='user', methods=['GET'], website=True)
def csv_download(self, **kw):
csv = http.request.env['survey.survey'].generate_cert_report()
filename = 'Certification Report - {}.csv'.format(
datetime.now().strftime("%m/%d/%Y"))
headers = [
('Content-Type', 'application/octet-stream'),
('Content-Disposition', 'attachment; filename="%s"' % (filename))
]
return request.make_response(csv, headers=headers)

Loading CSV to Odoo

I would like to know if it is possible to directly import CSV file to Odoo using External API.
I have searched a bit and did not find a proper answer. Any link guidance would be appreciated.
Thanks!
You can use base_import module, you will need to properly configure your POST data if you want to use set_file controller, or use your own controller. For example, set_file controller function expects file body in file attribute, an import_id attribute (Integer value). Checkout the function definition:
class ImportController(http.Controller):
#http.route('/base_import/set_file', methods=['POST'])
def set_file(self, file, import_id, jsonp='callback'):
import_id = int(import_id)
written = request.env['base_import.import'].browse(import_id).write({
'file': file.read(),
'file_name': file.filename,
'file_type': file.content_type,
})
return 'window.top.%s(%s)' % (misc.html_escape(jsonp), json.dumps({'result': written}))

Django edit static content on live site

I am having real difficulty working out how I can edit the html and css on a live site via logging into the site as a privileged user in Django (if this is possible in Flask I may use it instead). For example modifying the background image used on a page. ckeditor allow you to do this for model fields:
class Post(models.Model):
content = RichTextField()
But not for the static html or css. How do people normally do this - make all changes on a test machine the push the .html and css to the live site? Ideally I want the designer to be able to log in and modify the site with a wysiwyg tool without needing a developer.
If you want to achieve editing of the layout files of the site like Wordpress does it for themes, you are going to need to implement an app to do that yourself, I'm not aware of any existing project that allows you to do that, in Django or in Flask.
In a nutshell, you need to pick out what files you want to expose and have a view where you load up the text file open(file), display it in a Django Form in a textarea, and save it back to the file again.
If you're editing css files, depending on your setup, you might need to trigger a collectstatic command on form save, so that the file goes where it is needed.
You could also use Ace Editor for easier code editing.
This is a stripped down example of what I used in a previous project for achieving this:
class EditFileView(FormView):
template_name = "file_edit_form.html"
form_class = EditFileForm
ALLOWED_ROOTS = ["%s/" % DISPLAY_TEMPLATES_DIRECTORY, ]
def get_allowed_roots(self):
return self.ALLOWED_ROOTS
def dispatch(self, request, *args, **kwargs):
if "file_name" not in request.GET:
raise Http404
file_name = request.GET['file_name']
exists = False
for root in self.get_allowed_roots():
exists = os.path.exists(os.path.join(root, file_name))
if exists:
self.file_path = os.path.join(root, file_name)
self.file_name = file_name
self.root = root
break
if not exists:
logger.debug(u"EditFileView: Could not find file to edit - %s" % file_name)
raise Http404()
return super(EditFileView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
try:
f = open(self.file_path, "wt")
f.write(form.cleaned_data['file_contents'])
f.close()
except Exception, e:
pass
return HttpResponseRedirect(self.get_success_url())
def get_initial(self):
initial = super(EditFileView, self).get_initial()
with open("%s" % self.file_path, "r") as f:
initial['file_contents'] = f.read()
initial["file_path"] = self.file_path
return initial
def get_success_url(self):
return reverse("edit_file") + "?file_name=%s" % self.file_name
def get_context_data(self, **kwargs):
current = super(EditFileView, self).get_context_data(**kwargs)
current.update({"file_name": self.file_path[len(self.root):].replace("//", "/")})
return current

ViewBag content not shown when page reload

I am doing my project in mvc
i have controller to upload file in to a folder
public ActionResult UploadFile(HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file == null) { ModelState.AddModelError("File", "Please Upload Your file"); }
else if (file.ContentLength > 0)
{
.................
else
{ //Excel file copied temporarily to temp folder
var filename = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/Uploads/"), filename);
file.SaveAs(path);
ModelState.Clear();
ViewBag.Message = "File uploaded successfully";
}
}
}
return RedirectToAction("UploadSTR", "Upload");
}
and my view is
#using (Html.BeginForm("UploadFile", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
File Path put type="file" name="file" id="file" />
<input type="submit" name="submit" value="Upload" id="btn" />
}
<p> Message:#ViewBag.Message</p>
my problem is that after submit, file is uploaded and the return to the same page .But ViewBag.Message = "File uploaded successfully" is no shown in my view
If you use a view model, you can add the message as a hidden form value using the Html.HiddenFor() helper in your view. This way the value would get posted back into the model on form submission. You're probably not going to get the functionality you need using the ViewBag.
The ViewBag has certain uses where it is advantageous to use it, like for setting the page title in a layout. But in general the ViewBag is a beginner level item that you should probably look towards abandoning in favour of view models, to make use of MVC's powerful automatic view model binding features.
Maybe have a run through the MVC Music Store example or Google for other examples of using view models in ASP.NET MVC.
You can not pass data via ViewBag (and ViewData) during redirection, you need to avoid redirection or to use TempData. About TempData you can read here ViewBag, ViewData and TempData .
ViewBag will not survive redirect. Use TempData instead.