Flutter Zip & Unzip - flutter

Hello i want to ask how to zip and unzip become string in flutter :
Example :
final int BUFFER_SIZE = 40;
ByteArrayInputStream is = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(is, BUFFER_SIZE);
StringBuilder string = new StringBuilder();
byte[] data = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = gis.read(data)) != -1) { string.append(new String(data, 0, bytesRead)); }
gis.close();
is.close();
return string.toString();

You can use archive plugin to zip and unzip files.
To unzip:
// Read the Zip file from disk.
final bytes = File('test.zip').readAsBytesSync();
// Decode the Zip file
final archive = ZipDecoder().decodeBytes(bytes);
// Extract the contents of the Zip archive to disk.
for (final file in archive) {
final filename = file.name;
if (file.isFile) {
final data = file.content as List<int>;
File('out/' + filename)
..createSync(recursive: true)
..writeAsBytesSync(data);
} else {
Directory('out/' + filename).create(recursive: true);
}
}
To create a zip file:
// Zip a directory to out.zip using the zipDirectory convenience method
var encoder = ZipFileEncoder();
encoder.zipDirectory(Directory('out'), filename: 'out.zip');

Related

how to download files from cache directory to Android download directory

I download files from FTP and store them in cache directory using path_provider package
Future<void> _fileMock(String strFileName) async {
try {
final Directory appDocDir = await getTemporaryDirectory()..createSync(recursive: true);
String appDocPath = appDocDir.path;
print('appDocPath : $appDocPath');
_file = File('$appDocPath/$strFileName');
setSavePath('$appDocPath/$strFileName');
print('file : $file');
}catch(e){
print('_fileMock Error : ${e.toString()}');
final File file = File('');
}
}
The path to the cache directory is /data/user/0/package name/cache/fileName
The file will download normally.
I want to copy or download files from the cache directory to the download directory. Attach an image.
Solved
Implement in JAVA and call with MethodChannel.
///JAVA
Map<String, String> arg = call.arguments();
String strPath = arg.get("path");
String strFileName = arg.get("fileName");
assert strPath != null;
File fP02 = new File(strPath);
File file;
try {
assert strFileName != null;
file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), strFileName);
Files.copy(fP02.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
result.success(file.getPath());
} catch (IOException e) {
e.printStackTrace();
}

Download link will download the file in system download path

Error Code with fileinnfo
FileInfo File = new FileInfo(Server.MapPath("/Content/ExcelFiles/SalesTarget.xlsx"));
if (File != null)
{
int Size = Convert.ToInt32(File.Length);
string FileName = File.FullName;
int Position = FileName.LastIndexOf("\\");
FileName = FileName.Substring(Position + 1);
string test = File.GetType().ToString();
string filepath = Server.MapPath("/Content/ExcelFiles/SalesTarget.xlsx");
string ContentType = MimeMapping.GetMimeMapping(Server.MapPath("/Content/ExcelFiles/SalesTarget.xlsx"));
byte[] FileData = new byte[Size];
char[] chars = Encoding.Unicode.GetChars(FileData);
StreamReader reader = new StreamReader(filepath);
reader.Read(chars, 0, Size); // Throwing error here
Response.ContentType = ContentType;
StringBuilder SB = new StringBuilder();
SB.Append("filename=");
SB.Append(FileName);
Response.AddHeader("Content-Disposition", SB.ToString());
Response.BinaryWrite(FileData);
Response.Flush();
Response.End();
//File..Read(FileData, 0, Size);
}
Running Code with Httppostedfile Class:
HttpPostedFileBase File = Request.Files["FileToLoad"];
if (File != null)
{
int Size = File.ContentLength;
if (Size <= 0)
{
ViewData["ERROR"] = "You uploaded an empty file,please browse a valid file to upload";
return View("../Shared/Error");
}
string FileName = File.FileName;
int Position = FileName.LastIndexOf("\\");
FileName = FileName.Substring(Position + 1);
string ContentType = File.ContentType;
byte[] FileData = new byte[Size];
File.InputStream.Read(FileData, 0, Size);
theModel.AddAFile(FileName, Size, ContentType, FileData);
}
I want to download existing file from directory instead of using httppostedfile, so I am getting error while reading file data.

Write files from multiple rest requests

I have a rest service written to receive a file and save it.
The problem is that when I receive more than 2 requests, the files are not written only the last request is taken into consideration and written.
Here is my code:
#POST
#RequestMapping(value = "/media/{mediaName}/{mediaType}")
#Produces(MediaType.APPLICATION_OCTET_STREAM)
#ResponseBody
public String updateResourceLocally(#FormDataParam("rawData") InputStream rawData, #PathVariable("mediaName") String mediaName, #PathVariable("mediaType") String mediaType) {
logger.info("Entering updateResourceLocally for " + jobId + "; for media type: " + mediaType);
final String storeDir = "/tmp/test/" + mediaName + ("/");
final String finalExtension = mediaType;
final InputStream finalRawData = rawData;
// new Thread(new Runnable() {
// public void run() {
// writeToFile(finalRawData, storeDir, finalExtension);
// }
// }).start();
writeToFile(finalRawData, storeDir, finalExtension);
// int poolSize = 100;
// ExecutorService executor = Executors.newFixedThreadPool(poolSize);
// executor.execute(new Runnable() {
// #Override
// public void run() {
// writeToFile(rawData, storeDir, finalExtension);
// }
// });
logger.info("File uploaded to : " + storeDir);
return "Success 200";
}
I tried to put the writeToFile into threads, but still no success. Here is what writeToFile does
public synchronized void writeToFile(InputStream rawData,
String uploadedFileLocation, String extension) {
StringBuilder finalFileName = null;
String currentIncrement = "";
String fileName = "raw";
try {
File file = new File(uploadedFileLocation);
if (!file.exists()) {
file.mkdirs();
}
while (true) {
finalFileName = new StringBuilder(fileName);
if (!currentIncrement.equals("")) {
finalFileName.append("_").append(currentIncrement).append(extension);
}
File f = new File(uploadedFileLocation + finalFileName);
if (f.exists()) {
if (currentIncrement.equals("")) {
currentIncrement = "1";
} else {
currentIncrement = (Integer.parseInt(currentIncrement) + 1) + "";
}
} else {
break;
}
}
int read = 0;
byte[] bytes = new byte[1024];
OutputStream out = new FileOutputStream(new File(uploadedFileLocation + finalFileName));
while ((read = rawData.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
The writeToFile creates a folder and writes a file, if the file already exists, it appends 1 and then increments the 1 accordingly and writes the file, so I would get raw.zip, raw-1.zip, etc.
I think the inputstream bytes are being lost, am I correct in my assumption?
NOTE: I do not have a UI client, I am using Poster a Firefox extension.
Update: What I am trying to achieve here is very simple
I receive number of requests with files attached
I need to save them. If the mediaName and mediaType are the same, then I need to append something to the filename and save it in the same location
If they are different I do not have a problem
The problem I am facing with the current code is that, when I post multiple time to the same URL, I have file-names created according to what I want, but the file content is not right, they vary depending on when the request came in and only the last POST's request is written properly.
Eg. I have a zip file of size 250MB, when I post 5 time, the 1st four will have random sizes and the 5th will have the complete 250MB, but the previous four should also have the same content.
You must separate the stream copy from the free filename assignation. The stream copy must be done within the calling thread (jersey service). Only the file naming operation must be common to all threads/requests.
Here is your code with a little refactoring :
getNextFilename
This file naming operation must be synchronized to guarantee each call gives a free name. This functions creates an empty file to guarantee the next call to work, because the function relies on file.exists().
public synchronized File getNextFilename(String uploadedFileLocation, String extension)
throws IOException
{
// This function MUST be synchronized to guarantee unicity of files names
// Synchronized functions must be the shortest possible to avoid threads waiting each other.
// No long job such as copying streams here !
String fileName = "raw";
//Create directories (if not already existing)
File dir = new File(uploadedFileLocation);
if (!dir.exists())
dir.mkdirs();
//Search for next free filename (raw.<extension>, else raw_<increment>.<extension>)
int currentIncrement = 0;
String finalFileName = fileName + "." + extension;
File f = new File(uploadedFileLocation + finalFileName);
while (f.exists())
{
currentIncrement++;
finalFileName = fileName + "_" + currentIncrement + "." + extension;
f = new File(uploadedFileLocation + finalFileName);
}
//Creates the file with size 0 in order to physically reserve the file "raw_<n>.extension",
//so the next call to getNextFilename will find it (f.exists) and will return "raw_<n+1>.extension"
f.createNewFile();
//The file exists, let the caller fill it...
return f;
}
writeToFile
Must not be synchronized !
public void writeToFile(InputStream rawData, String uploadedFileLocation, String extension)
throws IOException
{
//(1) Gets next available filename (creates the file with 0 size)
File file = getNextFilename(uploadedFileLocation, extension);
//(2) Copies data from inputStream to file
int read = 0;
byte[] bytes = new byte[1024];
OutputStream out = new FileOutputStream(file);
while ((read = rawData.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
}

I have jsp oage which upload form data and file upload also same time. But i got java.io.FileNotFoundException: when there isn't file upload

boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
System.out.println("multipart2");
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (item.isFormField()) //your code for getting form fields
{
if (item.getFieldName().equals("btn")) {
if (item.getString().equals("Submit")) {
String name = item.getFieldName();
String value = item.getString();
System.out.println("test2" + name + value);
}
if (item.getString().equals("Save as Draft")) {
System.out.println("hii hii2");
String name = item.getFieldName();
String value = item.getString();
}
}
} if (!item.isFormField()) {
String fileName = item.getName();
System.out.println("File Upload Named : " + fileName);
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
// System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
response.sendRedirect("/EventCalendar-war/pages/user_pages/user_create_event.jsp");
}
This is my code.When there is no file to upload I got java.io.FileNotFoundException .If file is upload with form data it's work fine.What is wrong with my code?

download file from url in gwt

I want to download a file from internet and I have url of that file . so I wrote a download servlet :
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String pathToDownload = request.getParameter("url");
URL url = new URL(pathToDownload);
URLConnection uc = url.openConnection();
String contentType = uc.getContentType();
int contentLength = uc.getContentLength();
InputStream is = uc.getInputStream();
response.setContentType(contentType);
// resp.setHeader("Content-Disposition", "attachment; filename*=\"utf-8''" + filename + "");
ServletOutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}
in this i want to show the popup when user clicks on file whether to save or not so there is
resp.setHeader("Content-Disposition", "attachment; filename*=\"utf-8''" + filename + "");
but I want the filename same as filename on internate so additionally what is needed in above snippet?
Cut substring from the last "/" to the end of the URL string - this is your file name.
String disposition = httpConn.getHeaderField("Content-Disposition");
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index != 0) {
fileName = disposition.substring(index + 9,
disposition.length());
}
} else {
// extracts file name from URL
fileName = link.substring(link.lastIndexOf("/") + 1,
link.length());
}