upload a file via RestEasy via MultipartOutput - java

I'm trying to programmatically upload a file to an enpoint via RestEasyClient.
File file = new File("/Users/michele/path/file.txt");
MultipartOutput multipartOutput = new MultipartOutput();
multipartOutput.addPart(file, MediaType.APPLICATION_OCTET_STREAM_TYPE, "file.txt");
Entity<MultipartOutput> entity = Entity.entity(multipartOutput, MediaType.MULTIPART_FORM_DATA_TYPE);
//client is an instance of org.jboss.resteasy.client.jaxrs.ResteasyClient
client
.target("http://localhost:8080/endpoint")
.request()
.post(entity);
The problem is that the backend does not "find" the file that I uploaded
backend code
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
List<FileItem> items = fileUpload.parseRequest(httpReq);
items is always empt.
Using MultipartFormDataOutput::addFormData, as described in many articles, works but does not fit my use case.
Also using apache.http.client.HttpClient works, but I prefer to avoid adding dependencies to my client.
Any ideas?

Found it.
The trick was to use MultipartFormDataOutput and to set the filename when adding a part
MultipartFormDataOutput multipartOutput = new MultipartFormDataOutput();
multipartOutput.addFormData("uploaded file", file, MediaType.APPLICATION_OCTET_STREAM_TYPE, "file.txt");

Related

Upload file using spark framework on Tomcat server

I want to know how to upload a file in Java 8 using Spark framework 2.6.0 on Tomcat server version 8.5.9. I found an example but only applies to the standard configuration of Spark (embedded jetty). http://sparkjava.com/documentation#examples-and-faq
I solved this issue using Apache Commons Fileupload:
File archivo = new File("MyPath");
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(archivo);
ServletFileUpload fileUpload = new ServletFileUpload(factory);
List<FileItem> items = fileUpload.parseRequest(request.raw());
FileItem item = items.stream()
.filter(e -> "file".equals(e.getFieldName()))
.findFirst().get();
String fileName = item.getName();
item.write(new File(archivo, fileName));

Java/Apache Tika: How to get the last modified/created attribute of a file from URL

I want to use Java to get the last modified time and the creation time of a file on an HTTP server. The file is located at a specific URL. The methods using URLConnection and HttpURLConnection yield the Last-Modified attribute from the HTTP header, but this is not the actual creation date of the file.
I have been reading that Apache Tika is the library for the job. However, I have not been able to find a working example that does what I want. The closest example is perhaps here. But when I run the code given in that post, it does not yield the last modified attribute.
I'm using partly an approach given in this answer that I think might work, but currently does not print anything.
Parser parser = new AutoDetectParser();
BodyContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
URI u = new URI("https://sec.gov/Archives/edgar/full-index/2015/QTR4/master.idx");
InputStream is = new BufferedInputStream(new FileInputStream(new File(u)));
parser.parse(is, handler, metadata, new ParseContext());
System.out.println("Creation Date" + metadata.get(Metadata.CREATION_DATE));
System.out.println("Last Modified Date" + metadata.get(Metadata.LAST_MODIFIED));
When you are downloading the file using URLConnection, the HTTP headers are hidden from Tika.
All what Tika can read here is the same than if you had saved your file and opened a stream on it
It means that creation date and last modified will be the ones used when saving the file (the same that you can see using your OS browser [Windows explorer, nautilus...]).
If you need to read HTTP headers on that file and only that, do not use Tika but either directly the HTTPUrlConnection or any other HTTP client like (https://hc.apache.org/httpcomponents-client-4.5.x/) or the methods proposed in this other question.

Re usable, thread safe cmponents in commons-fileupload

I am using commons-fileupload to read image file from the POST request using classes DiskFileItemFactory and ServletFileUpload.
Can someone help me with which objects off the above can be re-used and accessed concurrently among threads or will have to be created anew for each request
Thanks in advance
Could not get any straight point in this direction.
But found the Streaming API of the commons file upload here.
Since it creates one ServletFileUpload object, So I think this migh be a better idea.
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
The documentation is not informative on this respect. The available examples suggest that all the objects are to be recreated on each request, except the FileCleaningTracker for which a static method is suggested when building the DiskFileItemFactories as shown in https://commons.apache.org/proper/commons-fileupload/using.html:
public static DiskFileItemFactory newDiskFileItemFactory(ServletContext context,
File repository) {
FileCleaningTracker fileCleaningTracker
= FileCleanerCleanup.getFileCleaningTracker(context);
DiskFileItemFactory factory
= new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD,
repository);
factory.setFileCleaningTracker(fileCleaningTracker);
return factory;
}

JSP Writing to server directory

So I am using resumable.js to upload files to a server.
The directory that I want to save to is something like
/dir/files/upload/
Obviously just made up, but this directory has user permissions to write to it.
I am using JSP to listen to the POST request that resumable.js makes, and writing the
.part
files to that directory.
Sample listener:
<% if(request.getMethod().equals("POST") && request.getParameter("resumableFilename") != null){
long chunkSize = StringUtils.isEmpty(request.getParameter("resumableChunkSize"))? 0:Long.parseLong(request.getParameter("resumableChunkSize"));
String fileName = request.getParameter("resumableFilename");
long totalSize = StringUtils.isEmpty(request.getParameter("resumableTotalSize"))? 0:Long.parseLong(request.getParameter("resumableTotalSize"));
String temp_dir = "/dir/files/upload/"+request.getParameter("resumableIdentifier");//Add in user_id
String dest_dir = temp_dir+fileName+".part"+request.getParameter("resumableChunkNumber");
File fDir = new File(temp_dir);
fDir.mkdirs();
if(ServletFileUpload.isMultipartContent(request)){
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(temp_dir)); ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request);
ArrayListIterator iter = (ArrayListIterator)items.iterator();
FileItem item = (FileItem)iter.next();
File fileWithNewDir = new File(dest_dir);
item.write(fileWithNewDir); // write file to dest_dir (fileName.part*CHUNK_NUM*)
}
}
%>
The script is hosted on
www.site.com/pubs/res.jsp
According to the JS itself for resumable, the process of uploading it gets completed, however, a new directory is not made at all. I know it's not the write permissions, so it must be something else.
Here is my call in javascript for a new resumable object
var resume = new Resumable({
target:"res.jsp",
resumableChunkSize: 1*1024*1024,
simultaneousUploads: 3,
testChunks: false,
throttleProgressCallbacks: 1
});
It seems to be hitting the jsp file, but nothing is happening.
I followed Apache's fileupload page in order to implement that listener, but maybe I went wrong at some point.
Apache's FileUpload
Resumable.js
Location of the directory matters. It has to be within the context of the WAR. You cannot write to any location outside the context of the container. If you look at the log you may be abe to see the error message which can explain this.

multipart/form-data not working with servlets

I am not really sure why the html form with the tag enctype="multipart/form-data" does not pass the objects it should pass. this is the case with mozilla and firefox.
for IEs case, for example, I use html control to choose a file, it does get what it is supposed to get.
Now I just want to know if there are any alternatives I can use to pass in files through http request object because the enctype="multipart/form-data" seems to be having some compatibility issues but I am not really sure
any suggestions would be appreciated! :D
First of all, you have to provide a little bit of code to show what you have done, and to know what went wrong. Anyway, I am assuming that you have to upload a file to the server using HTML file upload control.
File upload or to say multipart/form-data encoding type support is not implemented in HttpServlet implementation. So, the request.getParameter() don't work with multipart/form-data. You have to use additional libraries which provide support for this. Apache Commons File Upload is a good example. Their using fileupload guide will help you to get started with the library. Here is a simple example (compiled from using file upload guide).
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
// Process form field.
String name = item.getFieldName();
String value = item.getString();
} else {
// Process uploaded file.
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
if (writeToFile) {
File uploadedFile = new File("path/filename.txt");
item.write(uploadedFile);
}
}
}
} else {
// Normal request. request.getParameter will suffice.
}
got it. if someone else might have a problem like this, this was my problem. i checked the content type of the file for me to ensure that the objects passed is of a certain type. in IE, it returns application/x-zip-compressed THAT IS ONLY FOR IE but mozilla and chrome seems to be returning a different content type for the zip file which is application/octet-stream.
so i just added the application/octet-stream to the valid filetypes and it seems to be working now

Categories