Upload Servlet with custom file keys - eclipse

I have built a Server that you can upload files to and download, using Eclipse, servlet and jsp, it's all very new to me. (more info).
Currently the upload system works with the file's name. I want to programmatically assign each file a random key. And with that key the user can download the file. That means saving the data in a config file or something like : test.txt(file) fdjrke432(filekey). And when the user inputs the filekey the servlet will pass the file for download.
I have tried using a random string generator and renameTo(), for this. But it doesn't work the first time, only when I upload the same file again does it work. And this system is flawed, the user will receive the file "fdjrke432" instead of test.txt, their content is the same but you can see the problem.
Any thoughts, suggestions or solutions for my problem?

Well Sebek, I'm glad you asked!! This is quite an interesting one, there is no MAGIC way to do this. The answer is indeed to rename the file you uploaded. But I suggest adding the random string before the name of the file; like : fdjrke432test.txt.
Try this:
filekey= RenameRandom();
File renamedUploadFile = new File(uploadFolder + File.separator+ filekey+ fileName);
item.write(renamedUploadFile);
//remember to give the user the filekey
with
public String RenameRandom()
{
final int LENGTH = 8;
StringBuffer sb = new StringBuffer();
for (int x = 0; x < LENGTH; x++)
{
sb.append((char)((int)(Math.random()*26)+97));
}
System.out.println(sb.toString());
return sb.toString();
}
To delete or download the file from the server you will need to locate it, the user will input the key, you just need to search the upload folder for a file that begins with that key:
filekey= request.getParameter("filekey");
File f = new File(getServletContext().getRealPath("") + File.separator+"data");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(filekey);
}
});
String newfilename = matchingFiles[0].getName();
// now delete or download newfilename

Related

Modify this script to upload all files from google forms response to one folder in google drive

I found this script that will upload files from google forms response to a folder using the first response (name of applicant) to name the folder.
function onFormSubmit(e) {
const folderId = "###"; // ID of the destination folder
const form = FormApp.getActiveForm();
const formResponses = form.getResponses();
const itemResponses = formResponses[formResponses.length - 1].getItemResponses();
// Prepare the folder.
const destFolder = DriveApp.getFolderById(folderId);
const folderName = itemResponses[0].getResponse();
Logger.log(folderName)
const subFolder = destFolder.getFoldersByName(folderName);
const folder = subFolder.hasNext() ? subFolder.next() : destFolder.createFolder(folderName);
// Move files to the folder.
itemResponses[1].getResponse().forEach(id => DriveApp.getFileById(id).moveTo(folder));
}
I tried using it but it will only upload one file - the one correspnding to the specific question number in the line itemResponses[1].getResponse()
How Do i modify this script so it will upload all of the files in the response regardless of their position without creating multiple folders?
i.e. is it possible to set a range of questions that all the files will upload?
Also, i want to modify the script so that name of the folder will also consist of the response sequence number as a prefix to the name of responder, how is that possible?

Protractor - Create a txt file as report with the "Expect..." result

I'm trying to create a report for my scenario, I want to execute some validations and add the retults in a string, then, write this string in a TXT file (for each validation I would like to add the result and execute again till the last item), something like this:
it ("Perform the loop to search for different strings", function()
{
browser.waitForAngularEnabled(false);
browser.get("http://WebSite.es");
//strings[] contains 57 strings inside the json file
for (var i = 0; i == jsonfile.strings.length ; ++i)
{
var valuetoInput = json.Strings[i];
var writeInFile;
browser.wait;
httpGet("http://website.es/search/offers/list/"+valuetoInput+"?page=1&pages=3&limit=20").then(function(result) {
writeInFile = writeInFile + "Validation for String: "+ json.Strings[i] + " Results is: " + expect(result.statusCode).toBe(200) + "\n";
});
if (i == jsonfile.strings.length)
{
console.log("Executions finished");
var fs = require('fs');
var outputFilename = "Output.txt";
fs.writeFile(outputFilename, "Validation of Get requests with each string:\n " + writeInFile, function(err) {
if(err)
{
console.log(err);
}
else {
console.log("File saved to " + outputFilename);
}
});
}
};
});
But when I check my file I only get the first row writen in the way I want and nothing else, could you please let me know what am I doing wrong?
*The validation works properly in the screen for each of string in my file used as data base
**I'm a newbie with protractor
Thank you a lot!!
writeFile documentation
Asynchronously writes data to a file, replacing the file if it already
exists
You are overwriting the file every time, which is why it only has 1 line.
The easiest way would probably (my opinion) be appendFile. It writes to a file without overwriting existing data and will also create the file if it doesnt exist in the first place.
You could also re-read that log file, store that data in a variable, and re-write to that file with the old AND new data included in it. You could also create a writeStream etc.
There are quite a few ways to go about it and plenty of other answers
on SO specifically on those functions that can provide more info.
Node.js Write a line into a .txt file
Node.js read and write file lines
Final note, if you are using Jasmine you can also create a custom jasmine reporter. They have methods that contain exactly what you want (status Pass/Fail, actual vs expected values etc) and it's fairly easy to set up with Protractor

how to zip all files with asp.net 3.5

i 'm .net developer. i want to Zip all files and make a one zip file with this technique.
ZipFile multipleFilesAsZipFile = new ZipFile();
Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".zip");
Response.ContentType = "application/zip";
for (int i = 0; i < filename.Length; i++)
{
string filePath = Server.MapPath("~/PostFiles/" + filename[i]);
multipleFilesAsZipFile.AddFile(filePath, string.Empty);
}
multipleFilesAsZipFile.Save(Response.OutputStream);
how ever for making this Zip i use third party library Ionic.
all files are ziped successfully but not extracted to client desktop. is there problem with my code. or this library that i'm using has been expired.
Is there free full version .net compatible library to zip all files.
Use SharpZipLib:
Nuget Package
Install-Package SharpZipLib
OR Download here
http://www.icsharpcode.net/OpenSource/SharpZipLib/
Snippet from examples:
private void CompressFolder(string path, ZipOutputStream zipStream, int folderOffset) {
string[] files = Directory.GetFiles(path);
foreach (string filename in files) {
FileInfo fi = new FileInfo(filename);
string entryName = filename.Substring(folderOffset); // Makes the name in zip based on the folder
entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction
ZipEntry newEntry = new ZipEntry(entryName);
newEntry.DateTime = fi.LastWriteTime; // Note the zip format stores 2 second granularity
// Specifying the AESKeySize triggers AES encryption. Allowable values are 0 (off), 128 or 256.
// A password on the ZipOutputStream is required if using AES.
// newEntry.AESKeySize = 256;
// To permit the zip to be unpacked by built-in extractor in WinXP and Server2003, WinZip 8, Java, and other older code,
// you need to do one of the following: Specify UseZip64.Off, or set the Size.
// If the file may be bigger than 4GB, or you do not need WinXP built-in compatibility, you do not need either,
// but the zip will be in Zip64 format which not all utilities can understand.
// zipStream.UseZip64 = UseZip64.Off;
newEntry.Size = fi.Length;
zipStream.PutNextEntry(newEntry);
// Zip the file in buffered chunks
// the "using" will close the stream even if an exception occurs
byte[ ] buffer = new byte[4096];
using (FileStream streamReader = File.OpenRead(filename)) {
StreamUtils.Copy(streamReader, zipStream, buffer);
}
zipStream.CloseEntry();
}
string[ ] folders = Directory.GetDirectories(path);
foreach (string folder in folders) {
CompressFolder(folder, zipStream, folderOffset);
}
}
Taken from : https://github.com/icsharpcode/SharpZipLib/wiki/Zip-Samples
Works awesome!

Get upload filename in eclipse using servlet

I have an application that uploads a file. I need to pass this file into another program but for that I need the file name only. Is there any simple code for that, using only Java or a servlet procedure?
while (files.hasMoreElements())
{
name = (String)files.nextElement();
type = multipartRequest.getContentType(name);
filename = multipartRequest.getFilesystemName(name);
originalFilename = multipartRequest.getOriginalFileName(name);
//extract the file extension - this can be use to reject a
//undesired file extension
extension1 = filename.substring
(filename.length() - 4, filename.length());
extension2 = originalFilename.substring
(originalFilename.length() - 4, originalFilename.length());
//return a File object for the specified uploaded file
File currentFile = multipartRequest.getFile(name);
//InputStream inputStream = new BufferedInputStream
(new FileInputStream(currentFile));
if(currentFile == null) {
out.println("There is no file selected!");
return;
}
There's a method in apache commons-io to get the file's extension. There's also guava Files class, with its getFileExtension method.

How to read a directory with using InputStream in eclipse plugin developement

I'm developing an eclipse plug-in and I need to traverse a directory and whole content of the directory. I found the method which reads a file in plug-in (bundleresource) as InputStream.
InputStream stream = Activator.class.getResourceAsStream("/dir1/dir2/file.ext");
this method works for files only. I need a way to read directories, list subdirectories and files like File.io.
Thanks.
Do you want to read a resource directory of your plugin? Otherwise you have to traverse a directory and open one stream per file:
String path = "c:\\temp\\";
File directory = new File(path);
if (directory.isDirectory()) {
String[] list = directory.list();
for (String entry : list) {
String absolutePath = path + entry;
System.out.println("processing " + absolutePath);
File file = new File(absolutePath);
if (file.isFile()) {
FileInputStream stream = new FileInputStream(file);
// use stream
stream.close();
}
}
}
If you want to traverse subdirectories as well you should wrap this into a recursive method, check if file is a directory and call the recursive method in this case.