Rails - Dragonfly image upload to OCI using angular frontend - angularjs

I am uploading a file in angular and returning rails params in imageData and imageContent variable. Then in rails controller, I try to create a temp file using those parameters and assign it to the dragonfly accessor attribute but it doesn't get uploaded on save. Though I've verified the file upload to OCI Object storage in rails console, its working fine.
dragonfly_accessor :logo do
storage_options do |attachment|
{
path: "brand_logos/"
}
end
end
decoded_data = Base64.decode64(params[:brand][:logo][:imageData]) # json parameter set in directive scope
file_name = params[:brand][:logo][:imagePath]
File.open(file_path, 'wb+') { |file| file.write(decoded_data) }
params[:brand][:logo][:tempfile] = file_path # json parameter set in directive scope

Related

Transform img from url to file in React

I have an autocomplete section that searches movies through MovieDB api.
The result of the api has a field called poster_path that contains the path where the image exists.
"poster_path": "/lRQiJXETkCnVVurHmglNvMXrZOx.jpg"
I have a react project for front-end and a spring boot project for backend.
The thing I want to do is to get the image convert it to file and the send it to the backend controller as a multipart file.
How can I convert the image from url to file in React?
I've tried this but re.data returns the byte array I think:
axios.get(e.image).then(re => {
setFile(re.data)
});
And here is the controller:
public ResponseEntity<Post> post(#RequestPart(required = false) MultipartFile file, #RequestPart #Valid PostResource postResource, Principal principal)

Download file from api in ReactJs

I have ASP.NET Core MVC back-end api. One controller returns File from server. Is there a way to make request to api route by [href] attribute of <a> tag? Looks like it tries to call React route but not make a request to server.
Also I made AJAX call to that controller and got back file as a string (screenshot is attached). Why is it a string, shouldn.t it be a byte array? How to build back file from that string? (it's a .pdf file). I have an empty PDF if use JavaScript new File([], 'name', {options}).
ASP.NET Core controller returns PDF this way:
return PhysicalFile(Path.GetFullPath(relativePath), "application/pdf", reportName);
In React I receive it as a string this way:
let stringPDFBinary = await ReportService.getReport(id, reportFileName)
I just need to download file from api by any way.
So, the answer is here: PDF is blank when downloading using javascript
The same problem. Let it be one more topic, easier to find for others. The AJAX response is encoded string. In request config set 'responseType = 'arraybuffer'' somehow and receiving pdf will not be blank. Solved.
I Just copied and pasted from the code source. The problem seems to be the same that i had:
Asp net controller:
[HttpGet]
[Route("File")]
[AllowAnonymous]
public IActionResult GetFile(string key)
{
var file = (FileCacheValue)_fileCache.Cache[key.Replace(" ", "+")];
if (file == null)
return NotFound();
Response.Headers["content-disposition"] = $"inline;filename={file.Name}.pdf";
return File(file.Data, "application/pdf");
}
In this case comes from a cache system. The data is a byte array.
Front-end React:
const onClick = () =>
{
window.open(pdfByteArray, '_blank', 'fullscreen=yes');
}
Exactly what i have. I just put the data on a new window and open the pdf.
The Ajax part is straight forward, get the value from the response and set it on a variable

How to set esFactory host address dynamically in elastic search using angular?

I have created a json which have the key value pair of my host address. I need to set the client host as the value which is mentioned in JSON?
app.service('client', function (esFactory) {
return client = esFactory({
host: 'http://192.168.1.76:9200'
});
});
Want to make the 'host:' value to be read from a property/JSON file.
Finally I found an alternate solution for this. Since my intention is to update the configuration details from a property file or JSON file, I done the same in another manner.Apart from calling the JSON/property file using http calls I statically maintained the JSON throughout in my application by importing using script tag in my html. The problem which I faced during using http calls is time delay. The host will default assign to localhost address before completing the ajax call for JSON reading and to take the content from JSON. So when we mention the JSON file in script tags in html page it will load on when DOM creates and then we can access the data in JSON every were in our js.
You can use like this
app.factory('elasticClient', ['esFactory', function (esFactory) {
return esFactory({
host: 'http://localhost:9200',
sniffOnStart: true,
sniffInterval: 300000
});
}]);
Please check AngularJS-ElasticSearch

Capybara attach_file method not uploading a file

When a user on our website wants to create a new Object, they are required to upload an XML file, which is then passed to a controller action using AJAX. The controller method parses attributes from the XML file and passes them back to the JavaScript, which then auto-populates most of the new Object form fields.
The HTML looks like this:
<input type="file" name="upload_datafile" id="upload_datafile" accept=".xml">
The file is pulled from the file input using the following:
$("#upload_datafile").change(function() {
var file = $("#upload_datafile").prop("files")[0];
...
The Capybara test looks like this:
scenario 'upload file', js: true do
expect(page).to have_css '#upload_datafile'
attach_file('upload_datafile', File.expand_path('spec/fixtures/files/valid.xml'))
expect(page).to have_field 'name', with: 'Valid Object'
end
The 'name' field should be populated when 'valid.xml' is uploaded and has been parsed. Instead, our XML parser, which tries to read the file, throws the following error:
NoMethodError:
undefined method 'read' for "undefined":String
I have tested this extensively manually and no error is thrown. The file path is also correct in the Capybara test. If I throw a breakpoint into the Capybara test I can manually upload a file in the browser and it will work just fine. It appears that Capybara is not uploading the file and and instead our JavaScript passes the string 'undefined' to the controller action because that's the result when trying to get the 0th file in the 'files' prop of the file input during the Capybara test.
Why isn't Capybara actually uploading the file and/or why isn't the file accessible through JavaScript?

Apache common file upload empty multipart item list

I have been trying to parse a multipart request by using apache commons file upload over JBOSS 5.1 .
The problem is when request is parsed, FileItem list is not being filled .(FileItem list is empty) Here is the code block that is working on windows but not on Unix :
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024*1024*3);
factory.setRepository(new File("/root/loads/temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(100000);
upload.setSizeMax(100000);
boolean isMulti =upload.isMultipartContent(request);
// Parse the request
try {
List<FileItem> items = upload.parseRequest(request);
Note : I am reaching the HTTPServletRequest via HttpEvent.getHTTPServletRequest().Also request has not being handled before.java version = 1.6_021
I found the solution, jboss security and our project's platform rules does not allow to access any file which are not in the specified directory.
I used jboss temp directory and can access the items in the request.

Resources