I am trying to send a picture to my java servlet (hosted on amazon ec2) to later transfer it to amazon s3 and wonder how to retrieve the Image from the post request.
Upload Code
The request is sent through iOS RestKit API like this (pic.imageData is a NSData type):
RKParams* params = [RKParams params];
[params setValue:pic.dateTaken forParam:#"dateTaken"];
[params setValue:pic.dateUploaded forParam:#"dateUploaded"];
[params setData:pic.imageData MIMEType:#"image/jpeg" forParam:#"image"];
[RKClient sharedClient].username = deviceID;
[RKClient sharedClient].password = sessionKey;
[RKClient sharedClient].authenticationType = RKRequestAuthenticationTypeHTTPBasic;
uploadPictureRequest = [[RKClient sharedClient] post:kUploadPictureServlet params:params delegate:self];
Parsing Code Stub
This is how I parse the other 2 parameters on the Java servlet:
double dateTaken = Double.parseDouble(req.getParameter("dateTaken"));
double dateUploaded = Double.parseDouble(req.getParameter("dateUploaded"));
Question
The question is: how do I retrieve and parse the image on my server?
Servlet 3.0 has support for reading multipart data. MutlipartConfig support in Servlet 3.0 If a servelt is annotated using #MutlipartConfig annotation, the container is responsible for making the Multipart parts available through
HttpServletRequest.getParts()
HttpServletRequest.getPart("name");
References:
Servlet 3.0 File Upload handing files and params
Servlet 3.0 File upload Example
Something along the lines of this, using Apache Commons FileUpload:
// or #SuppressWarnings("unchecked")
#SuppressWarnings("rawtypes")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (ServletFileUpload.isMultipartContent(request)) {
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload upload = new ServletFileUpload(factory);
try {
final List items = upload.parseRequest(request);
for (Iterator itr = items.iterator(); itr.hasNext();) {
final FileItem item = (FileItem) itr.next();
if (!item.isFormField()) {
/*
* TODO: (for you)
* 1. Verify that file item is an image type.
* 2. And do whatever you want with it.
*/
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}
Refer to the FileItem API reference doc to determine what to do next.
Related
I wonder if it is possible to show the input file to select in my Swagger UI when exposing the API.
I confirm that it is working perfectly when defining the endpoint as following:
public ResponseEntity<String> upload(#RequestPart MultipartFile file)
There is no doubt to show the file chooser when using MultipartFile.
And as I would like to upload big files, I have to use HttpServletRequest instead in order to upload the file as a stream. The endpoint will be then like:
public #ResponseBody Response<String> upload(HttpServletRequest request) {
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
// Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (!item.isFormField()) {
String filename = item.getName();
// Process the input stream
OutputStream out = new FileOutputStream(filename);
IOUtils.copy(stream, out);
stream.close();
out.close();
}
}
return new Response<String>(true, "Success", "");
}
The endpoint is working well using a curl command. But unfortunately when using the Swagger UI, I am not able to show the file chooser.
Does anyone faced the same case or knows if Swagger supports this feature?
I am writing a simple java servlet to upload files to a server location from any client. This is my servlet doPost method:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
response.setContentType("text/html");
boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
if(isMultiPart){
ServletFileUpload upload = new ServletFileUpload();
try{
FileItemIterator itr = upload.getItemIterator(request);
while(itr.hasNext()){
FileItemStream item = itr.next();
if(item.isFormField()){
String fieldName = item.getFieldName();
InputStream is = item.openStream();
byte[] b = new byte[is.available()];
is.read(b);
String value = new String(b);
response.getWriter().println(fieldName+":"+value+"</br>");
}else{
//String path = getServletContext().getRealPath("/");
String path = <server path>;
if(FileUpload.processFile(path, item) ){
response.getWriter().println("file uploaded successfully</br>");
}else{
response.getWriter().println("file uploading failed</br>");
}
}
}
}catch(FileUploadException fue){
fue.printStackTrace();
}
}
}
I now have a problem when I am uploading very big files. Incase there is a network error, I need to resend all the files to the server again, I would like to prepare a solution where the user can upload the files from the point where it stopped when the network error occurred.
Can someone help me with this? Thanks in advance.
Can anyone help me with this please?
Check out Fine Uploader.
Resume uploads from previous sessions.
File Chunking Partitioning.
I get gwt-upload working in a GAE application. As suggested, I implemented a Custom UploadAction to handle the storage of the file in the DataStore. The code goes like this:
public String executeAction(HttpServletRequest request,
List<FileItem> sessionFiles) throws UploadActionException {
logger.info("Starting: DatastoreUploadAction.executeAction");
String executeAction = super.executeAction(request, sessionFiles);
for (FileItem uploadedFile : sessionFiles) {
Long entityId = new Long(2001); // This is where i wanna use a request parameter
InputStream imgStream;
try {
imgStream = uploadedFile.getInputStream();
Blob attachment = new Blob(IOUtils.toByteArray(imgStream));
String contentType = uploadedFile.getContentType();
appointmentDao.setAppointmentAttachment(entityId, attachment,
contentType);
} catch (IOException e) {
logger.error("Unable to store file", e);
throw new UploadActionException(e);
}
}
return executeAction;
}
As you see, the DAO class requires the "EntityID" to store the uploaded file in the DataStore. Now i'm working with a hard-coded value and it goes fine, but i'd like to have the entityID sent by the client as a request parameter. The widget that does the upload is a MultiUploader:
private MultiUploader defaultUploader;
Is it posible to the MultiUploader -or any other Widget- to set a request parameter so i can use it in my UploadAction?
Yes, you can set it on your client-side code. There is method: MultiUploader #setServletPath(java.lang.String), for example:
final MultiUploader u = new MultiUploader();
...
...
...
u.setServletPath(u.getServletPath() + "?entityId="+myObject.getEntityId());
on server side:
String entityId= request.getParameter("entityId");
Read this for more information: Sending additional parameters to the servlet
I need to extract text from the word document uploaded by the user. I got the code to extract words from a document located on my m/c. But my requirement is to allow users to upload their own document using the upload button & read that document(I dont need to save that document). Can you please suggest me how to go about this? I need to know what all need to happen after clicking the upload button.
When the user uploads their file, grab the associated InputStream and store it to a variable, like inputStream. Then just take the example code, and replace this line:
fs = new POIFSFileSystem(new FileInputStream(filesname));
...with something like:
fs = new POIFSFileSystem(inputStream);
Should be simple enough, assuming that you already have a Servlet in place to handle the upload.
Edit:
Here are the basics of how the servlet could work, assuming that you are using commons-fileupload to parse the upload:
public class UploadServlet extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// 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);
//this assumes that the uploaded file is the only thing submitted by the form
//if not you need to iterate the list and find it
FileItem wordFile = items.get(0);
//get a stream that can be used to read the uploaded file
InputStream inputStream = wordFile.getInputStream();
//and the rest you already know...
}
}
I am trying to use the (flash based) YUI Uploader with a Java (Spring-based) back-end.
The typical way of uploading files in the Java Servlet world is to set the ENCTYPE='multipart/form-data' on the HTML form requesting the file from the user. With the right server side APIs (i.e. Commons FileUpload), it is possible to get the file on the server.
But I am stymied by how to achieve this with the YUI Uploader. I am able to reach the Java controller, and I am even able to extract the custom post values. But I have no idea how to extract the binary file data out of the request.
Has anyone out had any luck with a YUI uploader with a Java back-end?
To answer my own question, and to make a long story short, this snippet of code did the trick:
#Controller
#RequestMapping("/FileUploadController")
public class FileUploadController {
#RequestMapping(method = RequestMethod.POST)
protected ModelAndView onSubmit(HttpServletRequest request) throws Exception{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> /* FileItem */ items = upload.parseRequest(request);
for (FileItem fileItem : items) {
if (fileItem.isFormField()) {
// processFormField(fileItem);
} else {
File uploadedFile = new File("/tmp/junk/" + fileItem.getName());
fileItem.write(uploadedFile);
}
}
return new ModelAndView("index");
}
}
This example uses Spring, but you should be able to do exactly the same as long as you have HttpServletRequest object.