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.
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 have a local directory which contains some images. I am trying to display the list of images from the local directory but nothing is displayed. I am getting the error exception handling message that the directory is empty.I don't know what I am doing wrong.
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List imgUrlList = new ArrayList();
File imageDir = new File("/images");
File[] files=imageDir.listFiles();
if(files!=null) {
for (File imageFile : files) {
String imageFileName = imageFile.getName();
imgUrlList.add(imageFileName);
}
}
else {
System.out.println("directory is empty");
}
req.setAttribute("imgUrlList", imgUrlList);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/test/test.jsp");
dispatcher.forward(req, resp);
}
<c:forEach var="img" items="${imgUrlList}"> <img > </c:forEach>
I am trying to use jsp and java to display information read from a csv to a website. I'm using Tomcat v9.0 with Eclipse.
The java code works as expected when running it just in java—it reads the csv data into an ArrayList of Song objects. However, when running the jsp file, it throws a filenotfoundexception.
The original java code reads and parses the csv in the getter function of "ReadBillboardCSV" here:
public ArrayList<BillboardSong> getReadBillboardCSV() throws FileNotFoundException {
Reader in = new FileReader("testFile.csv");
ArrayList<BillboardSong> readSongs = new ArrayList<BillboardSong>();
try {
Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in);
for (CSVRecord record : records) {
BillboardSong newSong = new BillboardSong();
readSongs.add(newSong);
newSong.setPosition(Integer.parseInt(record.get(0)));
My servlet calls the getter, then sets the attribute.
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession ses = request.getSession(true);
ReadBillboardCSV readData = new ReadBillboardCSV();
ArrayList<BillboardSong> songsArray = readData.getReadBillboardCSV();
ses.setAttribute("billboardArray", songsArray);
}
Here is the main portion of the jsp:
<%
RequestDispatcher rd = request.getRequestDispatcher("/ServletOne");
rd.forward(request, response);
%>
Is there a reason it cannot read the file when I run it on Tomcat?
i have a requirement where i get byte array (byte[]) data from database, i need to save this data in a file and allow the user to save where ever he want to save, same as downloading the attachments.The file name and extension also i'm retrieving from database. I'm using java,spring-mvc for this.
Below is the code:
spring controller:
#RequestMapping(value="/getFile", method = RequestMethod.GET)
public ModelAndView getFile(HttpServletRequest request, HttpServletResponse response) {
ModelAndView mav = new ModelAndView();
//logic to get the data from database
byte[] documentData = document.getDOCUMENTData();
String documentName = document.getDOCUMENTTITLE();
String documentExt = document.getDocumentExtension();
}
Please suggest, i know that using java.io.*, i can write the byte[] data in file and give file name and extension by taking the values declared above, but how can i allow users when clicked on "download file" icon to write the data and save that file where ever he wants same as downloading the attachment.Please suggest. Once user clicks on download file icon control comes to above controller.Thanks.
--EDIT--
Modified code:
#RequestMapping(value="/getFile", method = RequestMethod.GET)
public ModelAndView getFile(HttpServletRequest request, HttpServletResponse response) {
ModelAndView mav = new ModelAndView();
//logic to get the data from database
byte[] documentData = document.getDOCUMENTData();
String documentName = document.getDOCUMENTTITLE();
String documentExt = document.getDocumentExtension();
response.setHeader("Content-Disposition", "attachment;filename="+userDoc.getDOCUMENT_TITLE());
long l = userDoc.getDOCUMENT_SIZE();
int size = (int)l;
response.setContentLength(size);
response.getWriter().write("hello");//i need to write byte[] but for test i kept string.
}
I want user to see save window so that he can save where ever he want same as downloading the attachments from mail.Thanks.
This is a code I'm usign for the same request
HTML page:
<h:commandButton value="Click Here to Download" action="#{reportBean.download}" />
BEAN:
public void download(){
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setHeader("Content-Disposition", "attachment;filename="+file.getName());
response.setContentLength((int) file.length());
ServletOutputStream out = null;
try {
FileInputStream input = new FileInputStream(file);
byte[] buffer = new byte[1024];
out = response.getOutputStream();
int i = 0;
while ((i = input.read(buffer)) != -1) {
out.write(buffer);
out.flush();
}
FacesContext.getCurrentInstance().getResponseComplete();
input.close();
} catch (IOException err) {
err.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException err) {
err.printStackTrace();
}
}
}
Just make sure you have a File object named file
You have two options to achieve this:
One is to write the file in your server's local filesystem in an internet accesible folder. You can configure which of your server's local folders are accesible from internet in your Apache/IIS serttings. Then you update your HTML so your "download file" link points to that file through an URL.
The other option is, like #an3sarmiento did, to return the file as a byte[] stream to the browser. For this option to work, you have to send, along with the file content, a response header in which you tell the browser you are returning a downloadable file as a stream. You do that with the line:
response.setHeader("Content-Disposition", "attachment;filename="+[your file name]);
response.setContentLength([your file's length or bytes count]);
response.getWriter.write([your file's content as byte array]);
In the line above I assume you are working with Java Servlets and you have an HttpServletResponse variable named reponse, which you will respond to the browser's HTTP POST or GET request.
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.