how to save files using fetch? - kotlin

So I use fecht to manage my app downloads, I have this code that I use in my download btn
private void createDirectoryAndSaveFile() {
File direct = new File(Environment.getExternalStorageDirectory() + "/Download/Audio");
if (!direct.exists()) {
File audioDirs = new File("/sdcard/Download/Audio/");
audioDirs.mkdirs();
}
}
This is suppose to create a folder in downloads directory
private void download(Content content){
String appDataDir = activity.getExternalCacheDir().getAbsolutePath();
String filename = content.audioUrl.split("/")[content.audioUrl.split("/").length-1];
String fileExtension = filename.split("\\.")[1];
if(fileExtension.equals("null")){
filename = filename.split("\\.")[0]+"."+"mp3";
}
String downloadFileDir = appDataDir+"/"+filename;
if (android.os.Build.VERSION.SDK_INT >= 30) {
downloadFileDir = "/storage/emulated/0/Android/media/pereira.audios.memes/cache/"+filename;
}
String finalDownloadFileDir = downloadFileDir;
if(new File(downloadFileDir).exists()){
updateShared(content.id);
MainActivity.onAfterAction.onAction(activity, ActionTypes.AUDIO_DOWNLOAD, () -> shareOut(finalDownloadFileDir));
}else{
Dialog dialogDownload = Utils.createDialog(activity, R.layout.downloading_file, false);
TextView size = dialogDownload.findViewById(R.id.size);
TextView progress = dialogDownload.findViewById(R.id.progress);
ImageView preview = dialogDownload.findViewById(R.id.preview);
size.setText(Utils.formatSize(activity.getApplicationContext(), content.size));
Picasso.get().load(content.icon).into(preview);
dialogDownload.show();
new DownloadManager(activity).downloadFile(content.audioUrl, downloadFileDir, data -> {
activity.runOnUiThread(() -> progress.setText(data.progress + "%"));
});
}
}
and this is the code for donwload... when i click the btn to download the file, it just srtarts to load and never ends... does anyone know how i can fix this?

Related

Download the file as a zip in ASP.NET Core

I am designing an educational site. When the user downloads a training course, I want this download (training course) to be done in the form of compression (zipper), please give a solution
My code:
public Tuple<byte[],string,string> DownloadFile(long episodeId)
{
var episode=_context.CourseEpisodes.Find(episodeId);
string filepath = Path.Combine(Directory.GetCurrentDirectory(),
"wwwroot/courseFiles",
episode.FileName);
string fileName = episode.FileName;
if(episode.IsFree)
{
byte[] file = System.IO.File.ReadAllBytes(filepath);
return Tuple.Create(file, "application/force-download",fileName);
}
if(_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
{
if(IsuserIncorse(_httpContextAccessor.HttpContext.User.Identity.Name,
episode.CourseId))
{
byte[] file = System.IO.File.ReadAllBytes(filepath);
return Tuple.Create(file, "application/force-download", fileName);
}
}
return null;
}
I write a demo to show how to download zip file from .net core:
First , Add NuGet package SharpZipLib , create an Image Folder in wwwroot and put some picture in it.
controller
public class HomeController : Controller
{
private IHostingEnvironment _IHosting;
public HomeController(IHostingEnvironment IHosting)
{
_IHosting = IHosting;
}
public IActionResult Index()
{
return View();
}
public FileResult DownLoadZip()
{
var webRoot = _IHosting.WebRootPath;
var fileName = "MyZip.zip";
var tempOutput = webRoot + "/Images/" + fileName;
using (ZipOutputStream IzipOutputStream = new ZipOutputStream(System.IO.File.Create(tempOutput)))
{
IzipOutputStream.SetLevel(9);
byte[] buffer = new byte[4096];
var imageList = new List<string>();
imageList.Add(webRoot + "/Images/1202.png");
imageList.Add(webRoot + "/Images/1data.png");
imageList.Add(webRoot + "/Images/aaa.png");
for (int i = 0; i < imageList.Count; i++)
{
ZipEntry entry = new ZipEntry(Path.GetFileName(imageList[i]));
entry.DateTime= DateTime.Now;
entry.IsUnicodeText = true;
IzipOutputStream.PutNextEntry(entry);
using (FileStream oFileStream = System.IO.File.OpenRead(imageList[i]))
{
int sourceBytes;
do
{
sourceBytes = oFileStream.Read(buffer, 0, buffer.Length);
IzipOutputStream.Write(buffer, 0, sourceBytes);
}while (sourceBytes > 0);
}
}
IzipOutputStream.Finish();
IzipOutputStream.Flush();
IzipOutputStream.Close();
}
byte[] finalResult = System.IO.File.ReadAllBytes(tempOutput);
if (System.IO.File.Exists(tempOutput)) {
System.IO.File.Delete(tempOutput);
}
if (finalResult == null || !finalResult.Any()) {
throw new Exception(String.Format("Nothing found"));
}
return File(finalResult, "application/zip", fileName);
}
}
when I click the downloadZip ,it will download a .zip file
The simple example that follows illustrates the use of the static ZipFile.CreateFromDirectory method which, despite the fact that it is in the System.IO.Compression namespace , actually resides in the System.IO.Compression.FileSystem assembly, so you need to add a reference to that in your controller.
[HttpPost]
public FileResult Download()
{
List<string> files = new List<string> { "filepath1", "filepath2" };
var archive = Server.MapPath("~/archive.zip");
var temp = Server.MapPath("~/temp");
// clear any existing archive
if (System.IO.File.Exists(archive))
{
System.IO.File.Delete(archive);
}
// empty the temp folder
Directory.EnumerateFiles(temp).ToList().ForEach(f => System.IO.File.Delete(f));
// copy the selected files to the temp folder
files.ForEach(f => System.IO.File.Copy(f, Path.Combine(temp, Path.GetFileName(f))));
// create a new archive
ZipFile.CreateFromDirectory(temp, archive);
return File(archive, "application/zip", "archive.zip");
}
Answer from Source - MikesDotNetting

Resizing and creating image thumbnail in ASP.NET-Core 2.2

I am trying to create a thumbnail image in asp.net-core 2.2 application but I keep getting the above error whenever it gets to the point of creating the thumbnail.
The main image creates and stores fine but it is not able to create the thumbnail. Please I will appreciate any guide to resolve the error
Here are my methods for storing the uploaded image. This one works as expected
using LazZiya.ImageResize;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace eSchool.Models.Utilities
{
public class FileUploadHelper
{
private readonly IHostingEnvironment host;
public FileUploadHelper(IHostingEnvironment _host)
{
host = _host;
}
public async Task<string> SaveFileAsync(IFormFile file, string pathToUplaod)
{
string webroot=host.WebRootPath;
string DesiredDirectoryLocation = Path.Combine(webroot,pathToUplaod);
if(!Directory.Exists(DesiredDirectoryLocation))
{
Directory.CreateDirectory(DesiredDirectoryLocation);
}
string imageUrl = string.Empty;
var filename = Path.GetRandomFileName();
var newfilename = CreateUniqueFileName(file);
string pathwithfileName = DesiredDirectoryLocation + "/" + newfilename;
using (var fileStream = new FileStream(pathwithfileName, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
imageUrl = newfilename;
return imageUrl;
}
I have tried two different methods to create the thumbnail but either of them gives the above error
Here are the two methods.
The first one is this:
public string CreateThumbImage(IFormFile uploadedFile, string desiredThumbPath,string desiredThumbFilename, int desiredThumbWidth, int desiredThumbHeight)
{
try
{
Stream filestream = uploadedFile.OpenReadStream();
Image thumbnailStream = Image.FromStream(filestream);
Image thumbnailImage = thumbnailStream.GetThumbnailImage(desiredThumbWidth, desiredThumbHeight, () => false, IntPtr.Zero);
string webroot = host.WebRootPath;
string DesiredDirectoryLocation = Path.Combine(webroot, desiredThumbPath);
if (!Directory.Exists(DesiredDirectoryLocation))
{
Directory.CreateDirectory(DesiredDirectoryLocation);
}
string thumbFullPathName = desiredThumbPath + "/" + desiredThumbFilename;
thumbnailImage.Save(thumbFullPathName);
return thumbFullPathName;
}
catch
{
throw;
}
}
And the second one is this:
public void ResizeImage(IFormFile uploadedFile, string desiredThumbPath, int desiredWidth=0, int desiredHeight=0)
{
if (uploadedFile.Length > 0)
{
using (var stream = uploadedFile.OpenReadStream())
{
var uploadedImage = System.Drawing.Image.FromStream(stream);
//decide how to scale dimensions
if (desiredHeight == 0 && desiredWidth > 0)
{
var img = ImageResize.ScaleByWidth(uploadedImage, desiredWidth); // returns System.Drawing.Image file
img.SaveAs(desiredThumbPath);
}
else if(desiredWidth == 0 && desiredHeight > 0)
{
var img = ImageResize.ScaleByHeight(uploadedImage, desiredHeight); // returns System.Drawing.Image file
img.SaveAs(desiredThumbPath);
}
else
{
var img = ImageResize.Scale(uploadedImage, desiredWidth,desiredHeight); // returns System.Drawing.Image file
img.SaveAs(desiredThumbPath);
}
}
}
return;
}
And this is where I call the methods:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
FileUploadHelper uploadHelper = new FileUploadHelper(_host);
if (EmailValidation.EmailExists(model.EmailAddress,_context))
{
ModelState.AddModelError("EmailAddress", "This email address is already registered with us.");
}
if (model.Photo != null)
{
string[] extensions = new string[] { ".jpeg",".jpg", ".gif", ".png" };
///Validate the type of the image file being uploaded
ResponseMsg fileTypeValidated = uploadHelper.ValidateFileExtension(model.Photo, extensions);
if (!fileTypeValidated.ResponseStatus)
{
ModelState.AddModelError("Photo", fileTypeValidated.ResponseDescription);
}
///Validate the size of the image file being uploaded
ResponseMsg fileSizeValidated = uploadHelper.ValidateFilesize(model.Photo, 1);
if (!fileSizeValidated.ResponseStatus)
{
ModelState.AddModelError("Photo", fileSizeValidated.ResponseDescription);
}
}
if (ModelState.IsValid)
{
try
{
Instructor instructor = new Instructor
{
Surname = model.Surname,
OtherNames = model.Othernames,
Email = model.EmailAddress,
UserName = model.EmailAddress,
PhoneNumber = model.PhoneNumber,
Gender = model.Gender,
StateId = model.ResidenceState,
LgaId = model.ResidenceLga,
DateOfBirth = model.DateOfBirth,
TimeRegistered = DateTime.Now
};
var photo = await uploadHelper.SaveFileAsync(model.Photo,"images/instructors");
//Create image thumbnail for the instructor photo
var photo_thumbnail = "images/instructors/thumbs/" + photo;
uploadHelper.CreateThumbImage(model.Photo, "images/instructors/thumbs/", photo, 100, 100);...
Please help me if you can point out where I am missing the right path or a better way to handle image thumbnail creation in ASP.NET-Core 2.* to fix the error.
Regards
The error came from the path of the thumbnail. The path given in the ResizeImage method does not indicate the filename of the thumbnail image. That is where the generic GDI+ error was coming from.
So using the ResizeImage method works when the path of the resized image (including the image filename) is correctly passed to the SaveAs method. Here is the working method:
public void ResizeImage(IFormFile uploadedFile, string desiredThumbPath, int desiredWidth=0, int desiredHeight=0)
{
string webroot = host.WebRootPath;
if (uploadedFile.Length > 0)
{
using (var stream = uploadedFile.OpenReadStream())
{
var uploadedImage = System.Drawing.Image.FromStream(stream);
//decide how to scale dimensions
if (desiredHeight == 0 && desiredWidth > 0)
{
var img = ImageResize.ScaleByWidth(uploadedImage, desiredWidth); // returns System.Drawing.Image file
img.SaveAs(Path.Combine(webroot,desiredThumbPath));
}
else if(desiredWidth == 0 && desiredHeight > 0)
{
var img = ImageResize.ScaleByHeight(uploadedImage, desiredHeight); // returns System.Drawing.Image file
img.SaveAs(Path.Combine(webroot,desiredThumbPath));
}
else
{
var img = ImageResize.Scale(uploadedImage, desiredWidth,desiredHeight); // returns System.Drawing.Image file
img.SaveAs(Path.Combine(webroot,desiredThumbPath));
}
}
}
return;
}
And the implementation is as follows:
//Create image thumbnail for the instructor photo
var photo_thumbnail = "images/instructors/thumbs/" + photo;
uploadHelper.ResizeImage(model.Photo, photo_thumbnail, 100);
Remember to include the following using statement in the parent class of uploadHelper that houses the ResizeImage method as follows:
using LazZiya.ImageResize;
Meanwhile, LazZiya.ImageResize is nugget package for managing image resizing in asp.net-core 2.1
See the github link for it Github link for LazZiya image nugget
So, that solves your image resizing problem in asp.net-core
Regards
Once file uploaded/saved to server. You can use following ASP.NET core middleware to serve image thumbnails.
https://github.com/osprakash/ImageThumbnail-aspnetcore
Configure middleware in startup.cs and pass thumbnail size like below :
Disclaimer : i"m the author of above open source package.

Delete button stops working sporadically, only on Windows, when using our editor plugin

We are developing a markdown editor plugin for eclipse. My colleagues who are using Windows 10 encounter a bug that causes keys to stop working. The most common key is delete, other times it is ctrl + s.
Here is the code for the editor extension:
public class MarkdownEditor extends AbstractTextEditor {
private Activator activator;
private MarkdownRenderer markdownRenderer;
private IWebBrowser browser;
public MarkdownEditor() throws FileNotFoundException {
setSourceViewerConfiguration(new TextSourceViewerConfiguration());
setDocumentProvider(new TextFileDocumentProvider());
// Activator manages connections to the Workbench
activator = Activator.getDefault();
markdownRenderer = new MarkdownRenderer();
}
private IFile saveMarkdown(IEditorInput editorInput, IDocument document, IProgressMonitor progressMonitor) {
IProject project = getCurrentProject(editorInput);
String mdFileName = editorInput.getName();
String fileName = mdFileName.substring(0, mdFileName.lastIndexOf('.'));
String htmlFileName = fileName + ".html";
IFile file = project.getFile(htmlFileName);
String markdownString = "<!DOCTYPE html>\n" + "<html>" + "<head>\n" + "<meta charset=\"utf-8\">\n" + "<title>"
+ htmlFileName + "</title>\n" + "</head>" + "<body>" + markdownRenderer.render(document.get())
+ "</body>\n" + "</html>";
try {
if (!project.isOpen())
project.open(progressMonitor);
if (file.exists())
file.delete(true, progressMonitor);
if (!file.exists()) {
byte[] bytes = markdownString.getBytes();
InputStream source = new ByteArrayInputStream(bytes);
file.create(source, IResource.NONE, progressMonitor);
}
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
private void loadFileInBrowser(IFile file) {
IWorkbench workbench = PlatformUI.getWorkbench();
try {
if (browser == null)
browser = workbench.getBrowserSupport().createBrowser(Activator.PLUGIN_ID);
URL htmlFile = FileLocator.toFileURL(file.getLocationURI().toURL());
browser.openURL(htmlFile);
IWorkbenchPartSite site = this.getSite();
IWorkbenchPart part = site.getPart();
site.getPage().activate(part);
} catch (IOException | PartInitException e) {
e.printStackTrace();
}
}
#Override
public void init(IEditorSite site, IEditorInput editorInput) throws PartInitException {
super.init(site, editorInput);
IDocumentProvider documentProvider = getDocumentProvider();
IDocument document = documentProvider.getDocument(editorInput);
IFile htmlFile = saveMarkdown(editorInput, document, null);
loadFileInBrowser(htmlFile);
}
#Override
public void doSave(IProgressMonitor progressMonitor) {
IDocumentProvider documentProvider = getDocumentProvider();
if (documentProvider == null)
return;
IEditorInput editorInput = getEditorInput();
IDocument document = documentProvider.getDocument(editorInput);
if (documentProvider.isDeleted(getEditorInput())) {
if (isSaveAsAllowed()) {
/*
* 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors.
* Changed Behavior to make sure that if called inside a regular save (because
* of deletion of input element) there is a way to report back to the caller.
*/
performSaveAs(progressMonitor);
} else {
}
} else {
// Convert document from string to string array with each instance a single line
// of the document
String[] stringArrayOfDocument = document.get().split("\n");
String[] formattedLines = PipeTableFormat.preprocess(stringArrayOfDocument);
StringBuilder builder = new StringBuilder();
for (String line : formattedLines) {
builder.append(line);
builder.append("\n");
}
String formattedDocument = builder.toString();
// Calculating the position of the cursor
ISelectionProvider selectionProvider = this.getSelectionProvider();
ISelection selection = selectionProvider.getSelection();
int cursorLength = 0;
if (selection instanceof ITextSelection) {
ITextSelection textSelection = (ITextSelection) selection;
cursorLength = textSelection.getOffset(); // etc.
activator.log(Integer.toString(cursorLength));
}
// This sets the cursor on at the start of the file
document.set(formattedDocument);
// Move the cursor
this.setHighlightRange(cursorLength, 0, true);
IFile htmlFile = saveMarkdown(editorInput, document, progressMonitor);
loadFileInBrowser(htmlFile);
performSave(false, progressMonitor);
}
}
private IProject getCurrentProject(IEditorInput editorInput) {
IProject project = editorInput.getAdapter(IProject.class);
if (project == null) {
IResource resource = editorInput.getAdapter(IResource.class);
if (resource != null) {
project = resource.getProject();
}
}
return project;
}
}
Here is the repository: https://github.com/borisv13/GitHub-Flavored-Markdown-Eclipse-Plugin
Any help is accepted

Wicket : FileUploadPage doesnt refresh the filepath

again, i got a problem with wicket. Im trying to upload data with my Class "FileUploadPanel", which is implemented on another Page "Class A":
Class A
...
/* uploadfields for Picture and Video */
ArrayList<String> picExt = new ArrayList<String>();
ArrayList<String> videoExt = new ArrayList<String>();
picExt.add("jpg");
videoExt.add("mp4");
final FileUploadPanel picUpload = new FileUploadPanel("picUpload", "C:\\", picExt);
final FileUploadPanel videoUpload = new FileUploadPanel("videoUpload", "C:\\", videoExt);
final Form form = new Form("form"){
protected void onSubmit() {
...
// Save the path of Video and Picture into Database
table.setVideo(videoUpload.getFilepath());
table.setPicture(picUpload.getFilepath());
...
}
...
Class FileUploadPanel
public class FileUploadPanel extends Panel {
private static final long serialVersionUID = -2059476447949908649L;
private FileUploadField fileUpload;
private String UPLOAD_FOLDER = "C:\\";
private String filepath = "";
private List<String> fileExtensions;
/**
* Constructor of this Class
* #param id the wicket-id
* #param uploadFolder the folder, in which the File will be uploaded
* #param fileExtensions List of Strings
*/
public FileUploadPanel(String id, String uploadFolder, List<String> fileExtensions) {
super(id);
this.UPLOAD_FOLDER = uploadFolder;
this.fileExtensions = fileExtensions;
add(fileUpload = new FileUploadField("fileUpload"));
}
#Override
public void onComponentTag(ComponentTag tag){
// If no file is selected on startup
if(fileUpload.getFileUpload() == null){
return;
}
final FileUpload uploadedFile = fileUpload.getFileUpload();
if (uploadedFile != null) {
// write to a new file,
File newFile = new File(UPLOAD_FOLDER
+ uploadedFile.getClientFileName());
filepath = UPLOAD_FOLDER + uploadedFile.getClientFileName();
// if file in upload-folder already exists -> delete it
if (newFile.exists()) {
newFile.delete();
}
try {
newFile.createNewFile();
uploadedFile.writeTo(newFile);
info("saved file: " + uploadedFile.getClientFileName());
} catch (Exception e) {
throw new IllegalStateException("Error");
}
}
}
public String getFilepath() {
return filepath;
}
}
Well, if i use the submit-Button on my "Class A", the Pic and Video get saved on C:\, which is quite good so far. I thought i finally get along with wicket, but i cheered too soon...
Problem: The correct path is not saved in the Database, which is handled in the Form of "Class A"
I really dont get it, because the onComponentTag(...) of my FileUploadPanel must be executed when using the submit-button. Thats because i added some validations like "picture must be a JPG or wont be saved" in onComponentTag(...) - and that worked. So im sure, the onComponentTag(...) is executed when the Submit-Button of the Form is used, which also means the filepath should be up-to-date.
What is it im doin wrong this time?
Thank in Advance!
Greeting
V1nc3nt
You are using
File newFile = new File(UPLOAD_FOLDER +
uploadedFile.getClientFileName());
this code to create a new File.
Instead of it you can try this one :
File file = new File(UPLOAD_FOLDER ,
uploadedFile.getClientFileName());
And then get the absolute path and save it:
newFile.getAbsolutePath();

Create multiple sharepoint list items based multiple uploaded files SP2010

I would like to create sharepoint list items based on selected multiple files from local drive. After uploading selected multiple files list should contains new list items (title is file name) with attachments (one attachment/uploaded file).
Ok I extended my custom webpart (with dynatree) on that list using http://www.plupload.com/ and creating page for saving attachments.
public partial class ImportMultipleFilesAsListItems : LayoutsPageBase
{
protected void Page_Load(object sender, EventArgs e)
{
//request form parameters comes from plupload
int parentFolderKey = int.Parse(Request.Form["key"]);
var file = Request.Files[0];
SPList list = SPContext.Current.Web.GetList(Request.Form["listUrl"]);
SPListItem folderItem = list.GetItemById(parentFolderKey);
if (folderItem != null)
{
string parentFolder = null;
if (folderItem.Folder != null)
{
parentFolder = folderItem.Folder.Url;
}
else
{
int slashIndx = folderItem.Url.LastIndexOf('/');
parentFolder = folderItem.Url.Substring(0, slashIndx);
}
SPListItem childFile = list.AddItem(parentFolder, SPFileSystemObjectType.File);
childFile["Title"] = file.FileName;
childFile["IsFolder"] = 0;
childFile["DocParentId"] = parentFolderKey;
childFile.UpdateOverwriteVersion();
byte[] data = new byte[file.ContentLength];
file.InputStream.Read(data, 0, file.ContentLength);
childFile.Attachments.AddNow(file.FileName, data);
}
}
}
$(function () {
var listInfo = new Object();
listInfo.key = null;
listInfo.listUrl = ctx.listUrlDir;
listInfo.__REQUESTDIGEST = $('#__REQUESTDIGEST').val();
$("#uploader").pluploadQueue({
// General settings
runtimes: 'browserplus,html5,html4',
url: $('#uploadMultipleFilesUrl').val(),
max_file_size: '50mb',
chunk_size: '1mb',
multipart_params: listInfo,
rename: true
});
// Client side form validation
$('form').submit(function (e) {
var uploader = $('#uploader').pluploadQueue();
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind('StateChanged', function () {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
$('form')[0].submit();
}
});
uploader.start();
} else {
alert('You must queue at least one file.');
}
return false;
});
$("#uploader").hide();
});