I'm uploading a file using primefaces components.
public void handleFileUpload(FileUploadEvent event) {
UploadedFile file = event.getFile();
}
For the further progress of the application, I have a function given from a library that I have to use. This function is only accepting a FileObject as input parameter.
How can I convert the UploadedFile (primefaces) to a FileObject (Apache Common)?
A workaround would be converting the UploadedFile to a File and then convert the file to a FileObject using VFS.getManager() and its functions. But to do this, I would have to save the file on the server and delete it later again.
I'm looking for a way, where I can convert the UploadedFile directly to a FileObject. Maybe by converting it to a bytearray first?
Glad for all suggestions.
Apache Commons VFS supports many different 'virtual file systems', one of them being 'RAM' which does not require storing in a real disk based file(system)
You can use it something like this (disclaimer: not tested)
public void handleFileUpload(FileUploadEvent event) {
UploadedFile file = event.getFile();
FileObject ram = VFS.getManager().resolveFile("ram:"+file.getFileName());
OutputStream os = ram.getContent().getOutputStream();
os.write(file.getContents());
ram.getContent().close();
// Use the ram FileObject
}
Maybe the easiest solution would be to simply build a custom implementation of FileObject that receives a FileUpload as a constructor parameter, extracts it's InputStream's contents and returns them as requested.
Look at the documentation to know the required methods.
Related
When I receive a file from C# to iformfile, how do I know the file path of that file?
If I don't know, how do I set the path?
public async Task<JObject> files(IFormFile files){
string filePath = "";
var fileStream = System.IO.File.OpenRead(filePath)
}
In this document, some instructions on IFormFile are introduced:
Files uploaded using the IFormFile technique are buffered in memory or on disk on the server before processing. Inside the action method, the IFormFile contents are accessible as a Stream.
So for IFormFile, you need to save it locally before using the local path.
For example:
// Uses Path.GetTempFileName to return a full path for a file, including the file name.
var filePath = Path.GetTempFileName();
using (var stream = System.IO.File.Create(filePath))
{
// The formFile is the method parameter which type is IFormFile
// Saves the files to the local file system using a file name generated by the app.
await formFile.CopyToAsync(stream);
}
After this, you can get the local file path, namely filePath.
all examples show how to read an xml from an local file. But how do I read a xml from a url or a stream and process it further?
Example: http://www.oreillynet.com/xml/blog/2006/03/hello_saxon_on_net_an_aspnet_i.html
thanks in advance
Look for XsltExamples.cs in the saxon-resources download available on both Sourceforge and www.saxonica.com. The very first example seems to do what you are asking for.
public static void ExampleSimple1(String sourceUri, String xsltUri) {
// Create a Processor instance.
Processor processor = new Processor();
// Load the source document
XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri));
// Create a transformer for the stylesheet.
XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(xsltUri)).Load();
// Set the root node of the source document to be the initial context node
transformer.InitialContextNode = input;
// Create a serializer
Serializer serializer = new Serializer();
serializer.SetOutputWriter(Console.Out);
// Transform the source XML to System.out.
transformer.Run(serializer);
}
Are you using an XmlDocument object for reading the XML? If so, you'll want XMLDocument.Load() method, which can take a file path or URL, TextReader or Stream as input.
Likewise, XDocument.Load()(msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.load(v=vs.110).aspx) has a similar set of overloads.
I use Glassfish 3.1.2.2, Sql Server 2005, PF 3.4 and Mojarra 2.1.6. Ide Eclipse Juno.
I use stored procedure, and add jar commons-io.1.4 and commons-fileupload.1.2.1
In database, we save all file (pdf, doc, xls, etc.) in varbinary.
I have these doubts:
How I can upload any file (pdf, doc, xls, etc.) with p:fileupload and save as varbinary file in the database?
How I can download any varbinary file of database with p:FileDownload?
How I can show pdf with p:media, recovering files varbinary from the database?
ONE QUESTION
How I can upload any file (pdf, doc, xls, etc.) with p: fileupload and save them to the database?
I undestood the p:fileupload, since documentation.
I use this method, handlerFileUpload, for upload a file. Firsts get the inputScream of the event
<p:fileUpload fileUploadListener="#{fileBean.handleFileUpload}" />
public class FileBean {
public void handleFileUpload(FileUploadEvent event) {
UploadedFile file = event.getFile();
//application code
}
}
I used file.getInputStream and sent the stored procedure a BinaryStream
setBinaryStream(4, inputStream, (int)inputStream.toString().getBytes().length);
This is good??
TWO QUESTION
How I can download any varbinary file with p:FileDownload?
I recover a varbinary since database with getBytes.
Remember I use the stored procedure.
This method is in a class with request scope.
public byte[] ArchivoBin(int CDTPEnlaceImagen, int iddoc) {
Context();
Null_Rs_and_Proc();
Connection(0);
PA(2, 51);
[b]byte[] file = null;[/b]
try {
setProc(getCon().prepareCall(getCall()));
getProc().setInt(1, CDTPEnlaceImagen);
getProc().setInt(2, iddoc);
setRs(getProc().executeQuery());
getRs().next();
[b]file = getRs().getBytes(1);[/b]
System.out.println(file);
}
catch(SQLException e) {
System.out.println("Exception ArchivoBin");
System.out.println(e);
}
CloseConnections();
return file;}
But, when i get the file in bytes, i convert a bytes to inputscream, and then inputscream to DefaultStreamedContent.
This part is a class with request scope.
byte[] bytes = null;
bytes = getRecuperarDatos().ArchivoBin(
1,
idarchivo);
//Archivo is a Session Scope
getArchivo().setFile(new DefaultStreamedContent(
[b]new ByteArrayInputStream(bytes)[/b],
"application/pdf",
nomArchivo));
The f:download not get the file correct, It is corrupt.
<h:commandButton value="Download">
[b]<p:fileDownload value="#{archivo.file}"[/b] />
</h:commandButton>
I don't know why this bad
THREE QUESTION
How I can show pdf with p:media, recovering varbinary files from the database?
This is similar to TWO QUESTION, p:media say
"An error has occurred while loading the PDF document"
All is solved, when i save the file in database with the method contents.
Specifically, with
public void SubirAlBaseDatos(FileUploadEvent e) {
bytes[] file = e.getFile().getContents();
);
thus, I can show in p:media, and donwload in p:filedownload.
Something insignificant was causing the problem.
Thank!! BalusC for your tips
source
Hi I'm new to using Amazon EMR and Hadoop. I was wondering how to read an external file (stored in S3) from an EMR job. For example, I have a file containing a long list of blacklisted strings. When my EMR job is processing my input, how do I get the job to read in this list of blacklisted strings beforehand in order to use it during processing?
I tried using a regular Java Scanner class and hardcoding the S3 path to the file but that didn't seem to work, although I could just be doing it wrong...
I'd do something like this (sorry code is scala not java, but it's the same)
Pass the path in as a argument to your main method
Set that as a property in your configuration
val conf = new Configuration()
conf.set("blacklist.file", args(0))
In the mapper's setup method, read the file:
var blacklist: List[String] = List()
override def setup(context: Context) {
val path = new Path(context.getConfiguration.get("blacklist.file"))
val fileSystem = FileSystem.get(path.toUri, context.getConfiguration)
blacklist = scala.io.Source.fromInputStream(fileSystem.open(path)).getLines.toList
}
It would be better if you may add this file to the distributed cache as follows :
...
String s3FilePath = args[0];
DistributedCache.addCacheFile(new URI(s3FilePath), conf);
...
Later, in configure() of your mapper/reducer, you can do the following:
...
Path s3FilePath;
#Override
public void configure(JobConf job) {
s3FilePath = DistributedCache.getLocalCacheFiles(job)[0];
FileInputStream fstream = new FileInputStream(s3FilePath.toString());
// Read the file and build a HashMap/List or something which can be accessed from map/reduce methods as desired.
...
}
I am building REST application. I want to upload a file and I want to save it for example in /WEB-INF/resource/uploads
How can I get path to this directory ? My Controller looks like this
#RequestMapping(value = "/admin/house/update", method = RequestMethod.POST)
public String updateHouse(House house, #RequestParam("file") MultipartFile file, Model model) {
try {
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (file.getSize() > 0) {
inputStream = file.getInputStream();
fileName = "D:/" + file.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
} catch(Exception ex) {
ex.printStackTrace();
}
model.addAttribute("step", 3);
this.houseDao.update(house);
return "houseAdmin";
}
Second question...what is the best place to upload user files ?
/WEB-INF is a bad place to try to store file uploads. There's no guarantee that this is an actual directory on the disk, and even if it is, the appserver may forbid write access to it.
Where you should store your files depends on what you want to do with them, and what operating system you're running on. Just pick somewhere outside of the webapp itself, is my advice. Perhaps create a dedicated directory
Also, the process of transferring the MultipartFile to another location is much simpler than you're making it out to be:
#RequestMapping(value = "/admin/house/update", method = RequestMethod.POST)
public String updateHouse(House house, #RequestParam("file") MultipartFile srcFile, Model model) throws IOException {
File destFile = new File("/path/to/the/target/file");
srcFile.transferTo(destFile); // easy!
model.addAttribute("step", 3);
this.houseDao.update(house);
return "houseAdmin";
}
You shouldn't store files in /WEB-INF/resource/uploads. This directory is either inside your WAR (if packaged) or exploded somewhere inside servlet container. The first destination is read-only and the latter should not be used for user files.
There are usually two places considered when storing uploaded files:
Some dedicated folder. Make sure users cannot access this directory directly (e.g. anonymous FTP folder). Note that once your application runs on more than one machine you won't have access to this folder. So consider some form of network synchronization or a shared network drive.
Database. This is controversial since binary files tend to occupy a lot of space. But this approach is a bit simpler when distributing your application.