Retrieve file from POST request with NanoHttpd - java

I am trying to use the NanoHttpd library to upload files to my Android server by using a POST request from a form. I do receive the POST request on the server side. My question is how to retrieve the file from the POST request so I can save it somewhere in the device memory.
the form :
<form action='?' method='post' enctype='multipart/form-data'>
<input type='file' name='file' />`enter code here`
<input type='submit'name='submit' value='Upload'/>
</form>
the serve method :
#Override
public Response serve (IHTTPSession session) {
Method method = session.getMethod();
String uri = session.getUri();
if (Method.POST.equals(method)) {
//get file from POST and save it in the device memory
}
...
}

Last night i found solution it's very easy to upload file....
First you have manage 'TempFileManager'. It's handle temp file directory so it' create file and delete automatically after your work finish like copy,read,edit,move etc...
server.setTempFileManagerFactory(new ExampleManagerFactory());
So now you not have manage temp file it's work automatically...
Manage post request like this
private Response POST(IHTTPSession) {
try {
Map<String, String> files = new HashMap<String, String>();
session.parseBody(files);
Set<String> keys = files.keySet();
for(String key: keys){
String name = key;
String loaction = files.get(key);
File tempfile = new File(loaction);
Files.copy(tempfile.toPath(), new File("destinamtio_path"+name).toPath(), StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException | ResponseException e) {
System.out.println("i am error file upload post ");
e.printStackTrace();
}
return createResponse(Status.OK, NanoHTTPD.MIME_PLAINTEXT, "ok i am ");
}

Related

How to access the asset in workflow process step

I am trying to write a workflow process step for the DAM update asset such that the uploaded asset will be sent to an external service that will modify the asset and then the modified asset can be sent to the Metadata extraction step. So I've added my process step to the DAM update asset like this:
And my code looks like this so far:
public void execute(WorkItem item, WorkflowSession wfsession,MetaDataMap args) throws WorkflowException {
try
{
log.info("Here2 in execute method"); //ensure that the execute method is invoked
final Map<String, Object> map = new HashMap<String, Object>();
map.put( "user.jcr.session", wfsession.getSession());
ResourceResolver rr = resolverFactory.getResourceResolver(map);
String path = item.getWorkflowData().getPayload().toString();
log.info("Here2 path: " + path);
Resource resource = rr.getResource(path);
log.info("Here2 resource: " + resource);
InputStream is = resource.adaptTo(InputStream.class);
log.info("Here2 assets IS: " + is);
}
catch (Exception e)
{
log.info("Here Error");
e.printStackTrace();
}
}
This is what I see in the logs when I upload an asset:
Here2 in execute method
Here2 path: /content/dam/photo1.JPG/jcr:content/renditions/original
Here2 asset: null
Question
My external service has an API accepting requests over HTTP. How should I send over the asset to the external service?
Once the external service modifies the asset, what should I do so that the Metadata extraction step reads the modified asset instead of the original?
In order to access your external service via HTTP, you have to write a client. CQ provides commons-httpclient bundle and you may use it to access the service. Documentation for the library can be found here. I don't know if the service expects that the file will be send using PUT or POST, but httpclient provides all these methods. All you have to do is to provide appropriate InputStream. Adapt your resource to Rendition and use getStream() method to get the InputStream.
When you'll get the modified asset from the webservice, you need to replace the original one:
// rendition = ...; // original rendition object created as above
// newInputStream = ...; // new asset received from your webservice
Asset asset = rendition.getAsset();
asset.addRendition("original", newInputStream, rendition.getMimeType());

Uploading a file in Java Servlet

I have a Java Dynamic Web Project, and I'm using TomCat v7.0.
I am new to web projects and I didn't quite understand how I can upload a file in one of my jsp pages. Since my project is intended to be only local, I thought I could use a multipart form in which the person would choose the file (and this part goes fine) and later retreive the file path from my Servlet. I can't complete this part though, it appears to only give me the name of the file, not its entire path.
Can anyone point me to the right direction? I've read several posts about Apache File Upload and retreiving information from the multipart form but nothing seems to help me.
How can I get the file path from a form or alternatively how can I get the uploaded file to use in my Java classes?
Thanks in advance.
.jsp:
<form method="post" action="upload" enctype="multipart/form-data">
<input type="file" name="filePath" accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"></input>
<input type="submit" value="Enviar"></input>
</form>
Java Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("<html><body>");
try
{
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items)
{
if (item.isFormField())
{
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
out.println("<h1>"+fieldname+" / "+fieldvalue+"</h1>");
}
else
{
// Process form file field (input type="file").
String fieldname = item.getFieldName();
String filename = item.getName();
InputStream filecontent = item.getInputStream();
String s = filecontent.toString();
out.println("<h1>"+s+" / "+filename+"</h1>");
item.write(null);
}
}
}
catch (FileUploadException e)
{
throw new ServletException("Cannot parse multipart request.", e);
}
catch (Exception e)
{
e.printStackTrace();
}
out.println("</body></html>");
}
Not providing the file path is a security feature of the browser.
You have the file contents available in your code (InputStream filecontent) so you could use that or use one of the convenience methods on FileItem, e.g.
item.write(new File("/path/to/myfile.txt"));

How to read images from POST call parameter

I am looking at consuming an image that has been passed along with a post request as a parameter.
I am unable to understand how to consume this image with java restlet.
I want to use this image and send it for printing.
Thanks in advance.
Here is the code to put in a class extending ServerResource called at the POST of the form:
#Post
public Representation upload(Representation entity) throws Exception {
// 1/ Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// 2/ Create a new file upload handler based on the Restlet
// FileUpload extension that will parse Restlet requests and
// generates FileItems.
RestletFileUpload upload = new RestletFileUpload(factory);
// 3/ Request is parsed by the handler which generates a
// list of FileItems
List<FileItem> items = upload.parseRepresentation(entity);
String filename = "myImage.png";
File file = new File(filename);
for (FileItem fi : items) {
if (fi.getFieldName().equals("datafile")) {
System.out.println("Save image ... " + filename);
fi.write(file);
}
}
// Print your image
...
}

Test AJAX file upload

I want to test the file upload in my application. The upload itself is handled as described in section Direct file upload on http://www.playframework.org/documentation/2.0/JavaFileUpload.
I am using the latest Play20 version and build it as described here.
My current code looks like this, but obviously the part is missing which adds a test file to the request:
Test.java
FakeRequest request = fakeRequest(POST, "/measurement/123/file");
// how to append test file to this request?
Result result = routeAndCall(request);
assertOK(result);
Controller.java
public static uploadFile() {
RequestBody body = request().body();
if (body != null) {
RawBuffer rawBuffer = body.asRaw();
if (rawBuffer != null) {
File uploadedFile = rawBuffer.asFile();
// ...
}
}
return ok();
}
My solution for Play 2 Java file upload testing has been to create a UploadFakeRequest extending FakeRequest. Inside the class I have then my own withRawBody method with something like that:
RawBuffer raw = new RawBuffer(1000, data.getBytes()); // No clue what is the correct value here...
AnyContentAsRaw content = new AnyContentAsRaw(raw);
fake = new play.api.test.FakeRequest(POST, fake.path(), new play.api.test.FakeHeaders(Scala.asScala(map)), content, "127.0.0.1");
The signature of the FakeRequest call, as per source code, is:
case class FakeRequest[A](method: String, uri: String, headers: FakeHeaders, body: A) extends Request[A]
You should be able to inspect the body of a POST request that uploads a file to your application and copy that body as a parameter in your testing code. The alternative is to build it as per RFC description on multipart POST.

dwr - upload file and download file in one request

is it possible to upload a file and subsequently when receiving response download the file,
I mean in one request I'll upload a file and download the file in one action?
Maybe this demo code will be helpful for you:
http://directwebremoting.org/dwr-demo/simple/download.html
Yes It's possible to do that at least in dwr 3.
An example which return a excel to download from client:
//Java side:
public FileTransfer getExcel(Parametros param){
byte[] result = <here get data>;
InputStream myInputStream = new ByteArrayInputStream(result);
String excelFormat = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
FileTransfer dwrExcelFile = new FileTransfer("excel.xlsx", excelFormat, myInputStream);
return dwrExcelFile;
}
//Javascript side:
function downloadExcelFile() {
dwr.engine.setTimeout(59000);
var params = <params_to_send>;
<Java_class>.getExcel(params, {callback:function(dataFromServer) {
downloadExcelCallback(dataFromServer);
}});
}
function downloadExcelCallback(data) {
dwr.engine.openInDownload(data);
}

Categories