how to Upload File using Jersey - java

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>

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

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>

How can i upload and retrieve files (image,audio and video) in Spring MVC

I'm designing a small application in Spring MVC framework. I have a HTML page where user can upload multiple files.
Here is my HTML file:
<div class="form-group">
<label class="control-label col-sm-4" for="option1">Option 1:</label>
<div class="col-sm-4">
<form:input type="text" path="option1" class="form-control"/>
</div>
<div class="col-sm-4">
<form:input type="file" path="img1" class="form-control" name="img1"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="option2">Option 2:</label>
<div class="col-sm-4">
<form:input type="text" path="option2" class="form-control"/>
</div>
<div class="col-sm-4">
<form:input type="file" path="img2" class="form-control" name="img2"/>
</div>
</div>
based on this code I'm allowing the user to upload 2 files.
Also i have a bean called McqItem.java:
public class McqItem {
private String option1;
private String option2;
private byte[] img1;
private byte[] img2;
//with their getter and setters
}
In my controller i have designed a method where i pass all the data (option1 and option 2) to the bean and from there to the model and save them in my DB
BUT: I don't know how to save my files. prefer to save them in a file.
Can someone tell me how can I save the uploaded files?
You can use multi part file upload to upload and save files.
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(name)));
stream.write(bytes);
stream.close();
This sample from spring boot is a very good exampe
https://spring.io/guides/gs/uploading-files/
so here is what i have done after going through that link
Controller:
#RequestMapping(value="/questionType/MCQ.do",method = RequestMethod.POST)
public ModelAndView saveMCQuestion(#RequestParam("option1") String option1,#RequestParam("option2") String option2 ,#RequestParam("img1") MultipartFile img1,#RequestParam("img2") MultipartFile img2,#ModelAttribute McqItem mcqItem, HttpServletRequest request)throws IOException{
ModelAndView modelAndView = new ModelAndView();
QuizItem quizitem=(QuizItem)request.getSession().getAttribute("quizItem");
mcqItem.setQuiz_id(String.valueOf(quizitem.getId()));
QuizItem qType=(QuizItem)request.getSession().getAttribute("qTypeItem");
mcqItem.setQType(qType.getItemType());
//begin the uploading section
byte[] img1File=null;
byte[] img2File=null;
if(!img1.isEmpty() && !img2.isEmpty()){
try{
img1File= img1.getBytes();
img2File=img2.getBytes();
BufferedOutputStream stream=
new BufferedOutputStream(new FileOutputStream(new File(option1)));
stream.write(img1File);
stream.write(img2File);
stream.close();
System.out.println("Successful Upload");
}catch(Exception e){
return null;
} }
//end Uploading section
projectDAO.saveQuestion(mcqItem);
modelAndView.addObject("qtypeitem", new QuizItem());
modelAndView.setViewName("project/qType");
return modelAndView;
}
Basically my problem is that along my files i have a form to save in db as well.
But its giving me this error: "The current request is not a multipart request"

Categories

Resources