multipart form-data not working properly - java

In My JSP page I have three seperating forms with enctype ="multipart/form-data". On each of these forms I am uploading a file.
The first form is uploading the file correctly with type as application/pdf. But, the remaining two forms uploading the files as application/octet-stream.
The code as follows
<div id="form1" class="category-form" style="display:none;">
<form id="form" action="UploadServlet?action=form1" method="post" class="pure-form pure-form-aligned" enctype="multipart/form-data">
<div class="bottom fit" vertical layout>
<div style="margin-bottom: 1em">
<input id="file" name="file" type="file" data-placeholder="Attach file" class="filestyle" data-buttonName="btn-info">
</div>
</div>
</form>
</div>
<div id="form2" class="category-form" style="display:none;">
<form id="form" action="UploadServlet?action=form2" method="post" class="pure-form pure-form-aligned" enctype="multipart/form-data">
<div class="bottom fit" vertical layout>
<div style="margin-bottom: 1em">
<input id="file" name="file" type="file" data-placeholder="Attach file" class="filestyle" data-buttonName="btn-info">
</div>
</div>
</form>
</div>
<div id="form3" class="category-form" style="display:none;">
<form id="form" action="UploadServlet?action=form3" method="post" class="pure-form pure-form-aligned" enctype="multipart/form-data">
<div class="bottom fit" vertical layout>
<div style="margin-bottom: 1em">
<input id="file" name="file" type="file" data-placeholder="Attach file" class="filestyle" data-buttonName="btn-info">
</div>
</div>
</form>
</div>
My Servlet code as
#MultipartConfig(maxFileSize = 16177215)
public class UploadServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
doPost(req, res);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String action = request.getParameter("action");
if(action.equals("form1"))
{
Part filePart = request.getPart("file");
if (filePart != null)
{
System.out.println("File Parts Not Null");
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
System.out.println("File name is : "+filename);
inputStream = filePart.getInputStream();
}
}
if(action.equals("form2"))
{
Part filePart = request.getPart("file");
if (filePart != null)
{
System.out.println("File Parts Not Null");
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
System.out.println("File name is : "+filename);
inputStream = filePart.getInputStream();
}
}

Related

java servlet form fileupload broken in Internet Explorer with target="_blank"

My java file upload servlet is broken (InputStream is empty) in Internet Explorer 11 and Edge when I add target="_blank" to the form. It's working perfectly fine in Chrome and Firefox.
FileUploadServlet:
#WebServlet("/FileUploadServlet")
#MultipartConfig(fileSizeThreshold=1024*1024*10,
maxFileSize=1024*1024*50,
maxRequestSize=1024*1024*100)
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
for (Part part : request.getParts()) {
if(part.getName().equals("file")) {
System.out.println("stream length: " + part.getInputStream().available());
}
}
}
}
Working form:
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" />
</form>
Broken form:
<form action="FileUploadServlet" method="post" target="_blank" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
How can I get the form with target="_blank" also running in ie11?

Java: error parsing datetime (JSP, servlets)

I am trying to read a datetime value from a JSP form in my servlet:
ConcertController:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if ("add_concert".equals(action)) {
Concert concert = new Concert();
...
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
java.util.Date parsed = new java.util.Date();
try {
parsed = format.parse(request.getParameter("concert_datetime"));
} catch (ParseException e) {
e.printStackTrace();
}
java.sql.Date sqlDate = new java.sql.Date(parsed.getTime());
concert.setConcertTime(sqlDate);
..
));
concert.setTicketprice(Double.parseDouble(request.getParameter("concert_ticketprice")));
ConcertTable.insertConcert(concert);
request.getRequestDispatcher("ConcertsController?action=get_all_concerts").forward(request, response);
}
}
.jsp:
<form action="ConcertController?action=add_concert" method="post"
name="concertAddForm" id="formAddConcert"
enctype="multipart/form-data">
<h2>Add new concert</h2>
<div class="panel panel-success">
<div class="col-md-6 form-group">
<label>Concert name:</label> <input type="text" name="concert_name"
placeholder="Concert Name" class="form-control" required>
</div>
...
<div class="col-md-6 form-group">
<label>Date / Time:</label> <input type="text"
name="concert_datetime" placeholder="dd/MM/yyyy HH:mm"
class="form-control" required>
</div>
</div>
<br> <input type="submit" id="addConcertBtn"
class="btn btn-primary btn-large" value="Add concert">
</form>
but I keep getting an HTTP status 500:
java.lang.NullPointerException
java.text.SimpleDateFormat.parse(Unknown Source)
java.text.DateFormat.parse(Unknown Source)
I tried with 12/12/2000 20:00.
What am I doing wrong?
Eutherpy, if you don't need to upload files in your form, just get rid of
enctype="multipart/form-data"
Since it forces your form to be sent in multipart part format.
Otherwise, if you do need to upload files, there were several answers already.
You can have a look at this answer.

how to Upload File using Jersey

I'm trying to create service for uploading files.
I follow the guide https://examples.javacodegeeks.com/enterprise-java/rest/jersey/jersey-file-upload-example/
but when i'm trying to run i get
Status Code:405 Method Not Allowed
what i'm doing wrong?
here is my code
server
#Path("/doc")
public class DocResource extends BaseResource<DocDao, DocEntity>
{
#POST
#Path("/uploadDoc")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadFile(#Context HttpServletRequest req,
#FormDataParam("file") InputStream fileInputStream,
#FormDataParam("file") FormDataContentDisposition contentDispositionHeader) {
String filePath = SERVER_UPLOAD_LOCATION_FOLDER + contentDispositionHeader.getFileName();
// save the file to the server
saveFile(fileInputStream, filePath);
String output = "File saved to server location : " + filePath;
return output;
}
// save uploaded file to a defined location on the server
private void saveFile(InputStream uploadedInputStream,
String serverLocation) {
try {
OutputStream outpuStream = new FileOutputStream(new File(serverLocation));
int read = 0;
byte[] bytes = new byte[1024];
outpuStream = new FileOutputStream(new File(serverLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
outpuStream.write(bytes, 0, read);
}
outpuStream.flush();
outpuStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
HTML
<div class="modal fade" id="addEditDoc" tabindex="-1" role="dialog" aria-labelledby="addEditDoc" data-backdrop="false" data-keyboard="false">
<div class="modal-dialog addEditDocModal" role="document">
<div class="modal-content myModal">
<h1>Upload a File</h1>
<form action="http://127.0.0.1:8080/maintenance/uploadDoc" method="GET" enctype="multipart/form-data">
<p>
Select a file : <input type="file" name="file" size="50" />
</p>
<input type="submit" value="Upload It" />
</form>
</div>
</div>
</
I think the method must be POST instead of GET
Please find the further Documentation Here
<div class="modal-dialog addEditDocModal" role="document">
<div class="modal-content myModal">
<h1>Upload a File</h1>
<form action="http://127.0.0.1:8080/maintenance/doc/uploadDoc" method="POST" enctype="multipart/form-data">
<p>
Select a file : <input type="file" name="file" size="50" />
</p>
<input type="submit" value="Upload It" />
</form>
</div>
</div>

cannot read/ get file when try to upload using java struts action

i'm trying to upload excel file below my code:
im using bootstrap, blueimp plugin and struts action.
this is the request:
------WebKitFormBoundary5peQFGFm3lEKCOB5
Content-Disposition: form-data; name="fileName"
SMSMassploadOladDate.xls
------WebKitFormBoundary5peQFGFm3lEKCOB5
Content-Disposition: form-data; name="fileInput"; filename=""
Content-Type: application/octet-stream
------WebKitFormBoundary5peQFGFm3lEKCOB5
Content-Disposition: form-data; name="sub"
------WebKitFormBoundary5peQFGFm3lEKCOB5--
the file is being set null in java action
i was trying to get file using httpServletReques:
public String uploadMassContentsFromExcelSheetNew() {
HSSFSheet sheet = null;
HSSFWorkbook workbook = null;
FileInputStream inputStream = null;
result=new JSONObject();
try {
if (fileName != null){
fileName=fileName.trim();
if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx") ) {
String filePath = servletRequest.getSession().getServletContext().getRealPath("/");
servletRequest.getSession().getServletContext();
HttpServletRequest request = ServletActionContext.getRequest();
System.out.println("Parts*******:"+request.getParts()); //return null
Part filePart =request.getPart("fileInput");//return null
MultiPartRequestWrapper multiWrapper=(MultiPartRequestWrapper)ServletActionContext.getRequest();
File[] f=multiWrapper.getFiles("fileInput"); //return null
String fileName=multiWrapper.getFileNames("fileInput")[0];
Enumeration fileParameterNames = multiWrapper.getParameterNames();
String param = request.getParameter("fileInput");
}
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
jsp code:
<html>
<form name="massUploadForm" id="fileupload" action="uploadMassContentsFromExcelSheetNew.action" method="post" enctype="multipart/form-data" onsubmit="doMassValidate();">
<input type="hidden" id="fileName" name="fileName" value=""/>
<div id='fileDiv' class="row fileupload-buttonbar">
<div class="col-md-12 col-xs-12 col-lg-12">
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>addFile</span>
<input type="file" name="fileInput" id="fileInput" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
</span>
</div>
</div>
<table role="presentation" class="table table-striped">
<tbody class="files" id="addedFilesBody"></tbody>
</table>
<button name="sub" type="submit" ></button>
</form>
<html>

Liferay: How to make enctype="multipart/form-data" and method="post" work together?

I'm developing a web app using liferay portal server 6.2
JSP code -
<form id="mainForm" action="<portlet:actionURL/>" method="post" enctype="multipart/form-data" >
<input type="hidden" id="varImport" name="varImport"/>
<div class="tab-pane" id="uploadFile">
<p>Please upload a file</p>
<div id="inputFileDiv">
<input type="file" name="uploadFile" />
</div>
</div>
<input type="submit" class="btn btn-info" onClick="import()" value="IMPORT" />
</form>
<script>
function import() {
console.log("importing");
document.getElementById("varImport").value = "IMPORTFILE";
document.getElementById("mainForm").submit();
}
</script>
Servlet code -
#Override
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
System.out.println("myPortlet.processAction() >> " + request.getParameter("varImport"));
//... rest of the code.
}
If I remove enctype from jsp form, I get the value of varImport in my servlet.
But if i keep it, it returns null.
What am i missing?
import com.liferay.portal.util.PortalUtil;
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);
System.out.println("myPortlet.processAction() >> " + uploadRequest.getParameter("varImport"));

Categories

Resources