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

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>

Related

How to use getParts in java to get only image parts?

I'm trying to upload a file to cloudinary. I'm stucked at how to only get parts of image from the form. It keeps on throwing exception: Invalid image file. If I remove all text inputs in the form, the uploading is successful. I guess that happens because the form also has text inside. Please help me solve this. I'm really grateful for your support.
Here is my code:
Form.jsp:
<form role="form" action="<c:url value="/admin/product/update"/>" method="post" enctype="multipart/form-data">
<input name="id" value="${product.id}" hidden="">
<div class="form-group">
<label>Name:</label> <input class="form-control" value="${product.name}" name="name" />
</div>
<div class="form-group">
<label>Price:</label> <input class="form-control" value="${product.price}" type="number" name="price" />
</div>
<div class="form-group">
<label>Quantity:</label> <input class="form-control" value="${product.quantity}" type="number" name="quantity" />
</div>
<div class="form-group">
<label>Image:</label> <input class="form-control" value="${product.image}" name="image" />
</div>
<div class="form-group">
<label>Description </label> <br>
<textarea rows="4" cols="50" name="description" value="${product.description}" ></textarea>
</div>
<div class="form-group">
<label>Category</label>
<div class="checkbox">
<select name="catid">
<c:forEach items="${categorylist}" var="c">
<option value="${c.id}">${c.name}</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label>image</label> <input type="file" name="image" value="${product.image }" />
</div>
Servlet.java
BeanUtils.populate(product, request.getParameterMap());
//if (catid != product.getCategory().getId()) {
// Category category = new Category();
category = dao2.getCategoryByID(catid);
product.setCategory(category);
Map result = null;
Collection<Part> fileParts = request.getParts();
for (Part part : fileParts) {
String fileName = part.getSubmittedFileName();
result = UploadImage.uploadImage(fileName, part);
String url = String.valueOf(result.get("url"));
product.setImage(url);
if (result == null) {
throw new RuntimeException("Loi upload");
}
}
dao.update(product);
The Cloudinary upload method supports uploading media files from the sources like a local path, a remote URL, a private storage URL (S3 or Google Cloud storage), a base64 data URI, or an FTP URL.
Based on your code, it seems that you are only supplying the filename of the image.
String fileName = part.getSubmittedFileName();
result = UploadImage.uploadImage(fileName, part);
You would need to update the code to input the local path of the image.

How to Render uploaded Excel file in JSP Page from a Temp Folder?

I am not clear of rendering the uploaded Excel sheet into JSP Page
Here is the sample code of Uploading Excel
importExcel.jsp
<body>
<form:form method="POST" action="fileUpload" enctype="multipart/form-data">
<div class="upload">
<div class="upload-files">
<header>
<p>
<i class="fa fa-cloud-upload" aria-hidden="true"></i>
<span class="up">up</span>
<span class="load">Load</span>
</p>
</header>
<div class="body" id="drop">
<i class="fa fa-file-text-o pointer-none" aria-hidden="true"></i>
<p class="pointer-none"><b>Drag and drop</b> files here <br /> or browse to begin the upload</p>
<input type="file" name="xlsFile" accept=".xls,.xlsx" />
</div>
<footer>
<div class="divider">
<span><AR>FILES</AR></span>
</div>
<div class="list-files">
<!-- template -->
</div>
<button class="importar">UPDATE FILE</button>
</footer>
</div>
</div>
</form:form>
</body>
HomeController.java
#PostMapping("/fileUpload")
public String getFileUploadResult(#RequestParam("xlsFile") MultipartFile multiPartFile )throws Exception{
try {
if(multiPartFile!=null && !multiPartFile.isEmpty()){
byte[] fileBytes = multiPartFile.getBytes();
if(fileBytes!=null){
System.out.println("multiPartFile.getOriginalFilename() :: " +multiPartFile.getOriginalFilename());
Path internalPath=Paths.get(RAW_DATA_FILE_PATH+multiPartFile.getOriginalFilename());
if(internalPath!=null){
System.out.println("file written");
Files.write(internalPath,fileBytes);
}else{
System.out.println("internalPath is null");
}
}else{
System.out.println("fileBytes is null");
}
}else{
return "importExcel";
}
} catch (Exception e) {
throw e;
}
return "viewUploadedExcel";
}
I am in need to View the uploaded Excel file in viewUploadedExcel.jsp file, Since I am in research of this to bring out the solution and not yet met the expectation.
NOTE: I am working on JSP and Spring
Just set the mime/type in the response contentType to something like application/vnd.ms-excel, depending on the file format. Basing on file extension, xlsx would be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet. Then just use out.write the content of the uploaded file.
Obviously, the rendering of the excel by the browser depends on the browser.

multipart form-data not working properly

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();
}
}

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>

How to save event data into an xml file from dhtmlxscheduler

I need to save event data to an xml file.I need to do this using a java code.i am using html5.
So from the javascript i need to call this java code and need to save event text,date and other details to an xml file.And whenever the data is needed it should be displayed back in the dhtmlx scheduler.How can i do this?
function init() {
scheduler.config.xml_date="%Y-%m-%d %H:%i";
scheduler.config.prevent_cache = true;
scheduler.init('scheduler_here',new Date(2010,0,20),"month");
scheduler.load("data/data.xml");
}
function show() {
alert(scheduler.toXML());
}
function save() {
var form = document.forms[0];
form.action = "./data/xml_writer.php";
form.elements.data.value = scheduler.toXML();
form.submit();
}
function download() {
var form = document.forms[0];
form.action = "./data/xml_download.php";
form.elements.data.value = scheduler.toXML();
form.submit();
}
xml_writer.php
<?php
file_put_contents("./data.xml",$_POST["data"]);
header("Location:./dummy.html");
?>
<?php
if(empty($_POST['data'])) {
echo "why";
exit;
}
xml_download
$filename = "data.xml";
header("Cache-Control: ");
header("Content-type: text/plain");
header('Content-Disposition: attachment; filename="'.$filename.'"');
echo $_POST['data'];
?>
html code
<form action="./php/xml_writer.php" method="post" target="hidden_frame" accept-charset="utf-8">
<input type="hidden" name="data" value="" id="data">
</form>
<iframe src='about:blank' frameborder="0" style="width:0px; height:0px;" id="hidden_frame" name="hidden_frame"></iframe>
<div id="scheduler_here" class="dhx_cal_container" style='width:100%; height:100%;'>
<div class="dhx_cal_navline">
<div class="dhx_cal_prev_button"> </div>
<div class="dhx_cal_next_button"> </div>
<div class="dhx_cal_today_button"></div>
<div class="dhx_cal_date"></div>
<input type="button" name="download" value="Download" onclick="download()" style="right:500px;" />
<input type="button" name="show" value="Show" onclick="show()" style="right:400px;" />
<input type="button" name="save" value="Save" onclick="save()" style="right:300px;" />
<div class="dhx_cal_tab" name="day_tab" style="right:204px;"></div>
<div class="dhx_cal_tab" name="week_tab" style="right:140px;"></div>
<div class="dhx_cal_tab" name="month_tab" style="right:76px;"></div>
</div>
<div class="dhx_cal_header">
</div>
<div class="dhx_cal_data">
</div>
This much code i have.But code for saving to an xml file is in php.I need java code instead of php.

Categories

Resources