Is there any way to check if a asset file exists in Flutter before try to load the data?
For now I have the following:
String data;
try {
data = await rootBundle
.loadString('path/to/file.json');
} catch (Exception) {
print('file not found');
}
The problem is, that I have to check for file 1, if this does not exits I have to check for a fallback file (file 2) and if this does also not exist I load a third file.
My complete code would look like this:
try{
//load file 1
} catch (..) {
//file 1 not found
//load file 2
} catch (...) {
//file 2 not found
//load file 3
}
That looks very ugly to me, but I have no better idea...
AssetBundle (as returned by rootBundle) abstracts over different ways of loading assets (local file, network) and there is no general way of checking if it exists.
You can easily wrap your loading code so that it becomes less "ugly".
Future myLoadAsset(String path) async {
try {
return await rootBundle.loadString(path);
} catch(_) {
return null;
}
}
var assetPaths = ['file1path', 'file2path', 'file3path'];
var asset;
for(var assetPath in assetPaths) {
asset = await myLoadAsset(assetPath);
if(asset != null) {
break;
}
}
if(asset == null) {
throw "Asset and fallback assets couldn't be loaded";
}
I believe a better version is the one without the need to try/catch:
import 'dart:convert';
import 'package:flutter/services.dart';
Future<bool> isLocalAsset(final String assetPath) async {
final encoded = utf8.encoder.convert(Uri(path: Uri.encodeFull(assetPath)).path);
final asset = await ServicesBinding.instance.defaultBinaryMessenger.send('flutter/assets', encoded.buffer.asByteData());
return asset != null;
}
Related
I'm trying to build a web server in Rust, and i'm having a few issues trying to upload file into the server. With text based files it uploads fine, but whenever i try to upload other type of media (images, videos, etc), if the file is small enough, it will save, but corrupted, as showned.
original file raw data
file save on the server raw data
And when the file is too big, multer-rs library panicks with "received with incomplete data".
Error log
async fn parse_body(content_type: Option<&String>, body: String) -> HashMap<String, String> {
match content_type {
Some(content_type) => {
let ct = content_type.as_str();
if ct.contains("application/x-www-form-urlencoded") {
let buffer = body.replace("\r\n\r\n", "");
let _body = from_bytes::<Vec<(String, String)>>(buffer.as_bytes()).unwrap();
return _body.into_iter().collect();
}
if ct.contains("multipart/form-data") {
let boundary = multer::parse_boundary(ct).unwrap();
let data = once(async move { Result::<Bytes, Infallible>::Ok(Bytes::from(body)) });
let mut multipart = multer::Multipart::new(data, boundary);
let mut _body: HashMap<String, String> = HashMap::new();
// Iterate over the fields, use `next_field()` to get the next field.
while let Some(mut field) = multipart.next_field().await.unwrap() {
// Get field name.
let name = field.name().unwrap().to_string();
// Get the field's filename if provided in "Content-Disposition" header.
//
// Process the field data chunks e.g. store them in a file.
while let Some(chunk) = field.chunk().await.unwrap() {
// Do something with field chunk.
if let Some(file_name) = field.file_name() {
let file_dir = format!("src\\static\\temp\\{}", file_name);
let current_dir: &Path = Path::new(&file_dir);
let path = env::current_dir().unwrap().join(current_dir);
if let Ok(mut file) = std::fs::File::create(path) {
file.write_all(&chunk).unwrap();
}
} else {
_body.insert(name.clone(), String::from_utf8(chunk.to_vec()).unwrap());
}
}
}
return _body;
}
},
None => return HashMap::new()
}
HashMap::new()
}
How to search a specific named file in a folder using React ?
My file name is like below
var filename = window.location.hostname ;
Now I would like to search the file like below
if(require('../public/service/filename.json')) {
//do something
}
else {
//do something
}
You can use following way:
const checkFileExist = (path) => {
try {
return require(`${path}`);
} catch (err) {
return null;
}
};
and use it on your component
if(checkFileExist('../public/service/filename.json') === null) {
// something
} else {
// something
}
I use React-Intl in my app and it works great, but to be easier to manage new keys to translate I started using "react-intl-translations-manager".
My problem is that some of my translations are used through a notification system and the babel extractor don't recognize them because it's outside of his scan scope.
So when I run "react-intl-translations-manager" it deletes all the keys relatives to notifications and other non-scanned translations.
Here is my question: is there any method to "say" to "react-intl-translations-manager" that it's forbidden to delete those keys ?
I tried multiple solutions including whitelists and other but nothing is working.
Here is my translationRunner.js (the configuration file)
const manageTranslations = require('react-intl-translations-manager').default;
manageTranslations({
messagesDirectory: 'src/messages/',
translationsDirectory: 'src/locales/',
languages: ['en_GB', 'fr_FR']
});
There are two ways to do this. One is to use hooks and another way is to override the module where deletion of the actual code happens.
To do the same we can override the getLanguageReport module from react-intl-translations-manager/dist/getLanguageReport
getLanguageReport = require('react-intl-translations-manager/dist/getLanguageReport');
getLanguageReport.original = getLanguageReport.default
getLanguageReport.default = function(defaultMessages, languageMessages, languageWhitelist) {
data = getLanguageReport.original(defaultMessages, languageMessages, languageWhitelist)
// this whitelist ids can be read through a config file as well
whitelisted_id = ['helloworld2', 'helloworld']
deleted = data.deleted;
re_add = []
for (var i=0; i < deleted.length; ) {
if (whitelisted_id.indexOf(deleted[i].key)>=0) {
// we are removing a record so lets not increment i
removed_element = deleted.splice(i,1)[0];
data.fileOutput[removed_element.key] = removed_element.message;
} else {
i++;
}
}
return data;
}
const manageTranslations = require('react-intl-translations-manager').default;
manageTranslations({
messagesDirectory: 'build/messages/src/extracted/',
translationsDirectory: 'src/translations/locales/',
languages: ['de'] // Any translation --- don't include the default language
}
);
This method works fine and will keep the helloworld2 message even if it is not there in new code.
Hooks approach
In this we use the hook reportLanguage and override it to change the data
const manageTranslations = require('react-intl-translations-manager').default;
const writeFileSync = require('fs').writeFileSync
const stringify = require('react-intl-translations-manager/dist/stringify').default;
stringifyOpts = {
sortKeys: true,
space: 2,
trailingNewline: false,
};
manageTranslations({
messagesDirectory: 'build/messages/src/extracted/',
translationsDirectory: 'src/translations/locales/',
languages: ['de'], // Any translation --- don't include the default language
overrideCoreMethods: {
reportLanguage: function(langResults) {
data = langResults.report;
// this whitelist ids can be read through a config file as well
whitelisted_id = ['helloworld2', 'helloworld']
deleted = data.deleted;
re_add = []
for (var i=0; i < deleted.length; ) {
if (whitelisted_id.indexOf(deleted[i].key)>=0) {
// we are removing a record so lets not increment i
removed_element = deleted.splice(i,1)[0];
data.fileOutput[removed_element.key] = removed_element.message;
} else {
i++;
}
}
// original definition of reportLanguage from manageTranslations.js
// unfortunately the original core method is not exposed for us to re-use
// so we need to copy the code again
if (
!langResults.report.noTranslationFile &&
!langResults.report.noWhitelistFile
) {
// printers.printLanguageReport(langResults);
writeFileSync(
langResults.languageFilepath,
stringify(langResults.report.fileOutput, stringifyOpts)
);
writeFileSync(
langResults.whitelistFilepath,
stringify(langResults.report.whitelistOutput, stringifyOpts)
);
} else {
if (langResults.report.noTranslationFile) {
printers.printNoLanguageFile(langResults);
writeFileSync(
langResults,
stringify(langResults.report.fileOutput, stringifyOpts)
);
}
if (langResults.report.noWhitelistFile) {
printers.printNoLanguageWhitelistFile(langResults);
writeFileSync(
langResults.whitelistFilepath,
stringify([], stringifyOpts)
);
}
}
}
}
});
I want to download a file when clicking on a button in my AngularJS app which runs on Tomcat with a Java Spring backend but nothing is happening. The method in the backend is called and everything seems to have worked....but my browser doesn't download anything.
What am I missing?
Here's the AngularJS code, which logs Export-Response:[object Object]:
exportProjects() {
let filteredProjectIds = [];
for (let i in this.filteredProjects) {
for (let x = 0, l = this.filteredProjects[i].length; x < l; x++) {
if (!this.isOldProjectsBundle(this.filteredProjects[i][x])) {
filteredProjectIds.push(this.filteredProjects[i][x].id);
}
}
}
this.$http.get('/profiles/projectWordExport?filteredProjects=' + filteredProjectIds.join(",")).then(response => {
console.log("Export-Response:" + response);
return response;
});
}
This is the Java code being called (it's really being called, already debugged it, no errors occuring):
#RequestMapping(value = "/projectWordExport", method = RequestMethod.GET)
public void getProjectsWord(HttpServletRequest request, HttpServletResponse response, #RequestParam String filteredProjects) throws Exception {
//Load project objects from input string or load all projects if input empty
List<Project> projects = new java.util.ArrayList<>();
if (filteredProjects.isEmpty()) {
projects = projectRepository.findAll();
} else {
String[] pIds = filteredProjects.split(",");
for (String pId : pIds) {
projects.add(projectRepository.findById(Long.parseLong(pId)));
}
}
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.setHeader("Content-disposition", "attachment;filename=Projektexport.docx");
try {
SaveToZipFile saver = new SaveToZipFile(printer.printProjects(this.prepareProjectExport(projects)));
saver.save(response.getOutputStream());
response.flushBuffer();
} catch (NullPointerException e) {
response.setStatus(500);
response.sendError(500, "Fehler beim exportieren des Tests aufgetreten");
}
}
Put this in #RequestMapping annotation
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE
I need help on an mvc application in vb.net. In general terms I need to receive an image through the view and get it to work on the controller. I need to do this to convert the image to a byte array and save it to an oracle database. So my idea is to get the image and in the controller to convert it to a byte array or maybe there is some way to get the image already as a byte array and pass that array to the controller to save it to the database.
something like this its my View :
<div class="span11">
<div class="span4" id="depnac">
#Html.LabelFor(Function(m) m.DepNacPER)
#Html.DropDownListFor(Function(m) m.DepNacPER, Model.DepNacPER, New With {.class = "form-control"})
</div>
and this is my Model :
<Display(Name:="Region of birth")>
<Required(ErrorMessage:="you must select a option")>
Property DepNacPER As SelectList
I'm working on an ASP.NET Core app right now that uploads images. The image comes through to the controller via the request as a Stream. I'm then creating an Image object from that Stream but you could just read the data from it directly. That said, you might want to try to create an Image object to confirm that the data does represent a valid image.
Here's some relevant code from the view's script:
function uploadImage()
{
// This is a file upload control in a hidden div.
var image = $("#imageFile");
if (image[0].files.length > 0)
{
var formData = new FormData();
formData.append(image[0].files[0].name, image[0].files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "#Url.Content("~/events/uploadimage")");
xhr.send(formData);
xhr.onreadystatechange = function ()
{
if (xhr.readyState === 4 && xhr.status === 200)
{
var response = JSON.parse(xhr.responseText);
if (response.saveSuccessful)
{
// ...
} else
{
window.location.replace("#Url.Content("~/error")");
}
}
}
xhr.onerror = function(err, result)
{
alert("Error: " + err.responseText);
}
}
}
I'm in the process of replacing that code with some jQuery that does the heavy lifting but haven't got that far yet.
Here's some relevant code from the action:
[HttpPost]
public IActionResult UploadImage()
{
var requestForm = Request.Form;
StringValues tempImageFileNames;
string tempImageFileName = null;
string imageUrl = null;
var saveSuccessful = true;
var requestFiles = requestForm.Files;
if (requestFiles.Count > 0)
{
// A file has been uploaded.
var file = requestFiles[0];
using (var stream = file.OpenReadStream())
{
try
{
using (var originalImage = System.Drawing.Image.FromStream(stream))
{
// Do whatever you like with the Image here.
}
}
catch (Exception)
{
saveSuccessful = false;
}
}
}
if (saveSuccessful)
{
return Json(new {saveSuccessful, tempImageFileName, imageUrl});
}
else
{
return Json(new {saveSuccessful});
}
}
Sorry, it didn't occur to me at first that you're after VB code and this is C#. Hopefully you can still get the idea and I'll take the hit if someone dislikes the answer.