Not able to Stream video in Spring mvc - java

I am trying to pass video in bytes from controller and read and play it on jsp. It is working for videos having size less than 1 MB MB but it is not working for files bigger than 1 MB. Please help me..
here is my controller which reads file and writes bytes into output stream.
#RequestMapping(value = "/playVideo", method = RequestMethod.GET)
#ResponseBody
public void home(Locale locale, Model model,HttpServletRequest request,HttpServletResponse response) throws IOException {
logger.info("Welcome home! The client locale is {}.", locale);
String filePath = "D://Uploads//s.mp4";
int fileSize = (int) new File(filePath).length();
response.setContentLength(fileSize);
response.setContentType("video");
FileInputStream inputStream = new FileInputStream(filePath);
ServletOutputStream outputStream = response.getOutputStream();
int value = IOUtils.copy(inputStream, outputStream);
System.out.println("File Size :: "+fileSize);
System.out.println("Copied Bytes :: "+value);
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
response.setStatus(HttpServletResponse.SC_OK);
}
Here is my jsp page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<video width="320" height="240" controls>
<source src="/elearningportal/playVideo" type=video/mp4>
</video>
</body>
</html>

Have you tried using a bigger BufferSize?
response.setBufferSize(fileSize);

Related

How to pass the values from Spring controller to JSP

I have Spring controller and I am setting a model value and want to display in my JSP:
public class TestController {
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello(Model model){
model.addAttribute("message", "Programmer Gate");
return "/test";
}
}
My test.jsp code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Welcome</title>
</head>
<body>
<%
double num = Math.random();
if (num > 0.95) {
%>
<h2>You'll have a luck day!</h2><p>(<%= num %>)</p>
<%
} else {
%>
<h2>Well, life goes on ... </h2><p>(<%= num %>)</p>
<%
}
%>
<p>${message}</p>
</body>
</html>
I am not seeing the message value as the JSP rendering as follows:
Well, life goes on ...
(0.3343913194169942)
${message}
How to access the model message variable value in the JSP?

why inside eclipse browser able to upload and read image file while out side browser like chrome able to upload but not able to read image file? [duplicate]

This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 5 years ago.
I have three code file in which two are the jsp file and one servlet file created as follow :
servlet file UploadServlet.java
package net.codejava.servlet;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#WebServlet("/UploadServlet")
#MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
maxFileSize=1024*1024*10, // 10MB
maxRequestSize=1024*1024*50) // 50MB
public class UploadServlet extends HttpServlet {
/**
* Name of the directory where uploaded files will be saved, relative to
* the web application directory.
*/
private static final String SAVE_DIR = "uploadFiles";
/**
* handles file upload
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// gets absolute path of the web application
String appPath = request.getServletContext().getRealPath("");
// constructs path of the directory to save uploaded file
String savePath = appPath + File.separator + SAVE_DIR+ File.separator +"kala";
// creates the save directory if it does not exists
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
System.out.println(savePath);
//savePath="C:\\Users\\SANJAY GUPTA\\Downloads\\eclipse";
for (Part part : request.getParts()) {
String fileName = extractFileName(part);
// refines the fileName in case it is an absolute path
fileName = new File(fileName).getName();
part.write(savePath + File.separator + fileName);
}
request.setAttribute("message", "Upload has been done successfully!");
getServletContext().getRequestDispatcher("/message.jsp").forward(
request, response);
}
/**
* Extracts file name from HTTP header content-disposition
*/
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
return "";
}
}
first jsp file index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
<center>
<h1>File Upload</h1>
<form method="post" action="UploadServlet"
enctype="multipart/form-data">
Select file to upload: <input type="file" name="file" size="60" /><br />
<br /> <input type="submit" value="Upload" />
</form>
</center>
</body>
</html>
second jsp file message.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload</title>
</head>
<body>
<h2>${requestScope.message}</h2>
<%# page import="java.io.File"%>
<%
String SAVE_DIR = "uploadFiles";String appPath = request.getServletContext().getRealPath("");
String savePath = appPath + File.separator + SAVE_DIR+ File.separator +"kala"+ File.separator;
out.write("<h3>This is the Profile Picture</h3><br><br><button type=\"submit\" name=\"img\">"+
"<img src=\""+savePath+"333.jpg\" style=\"width:304px;height:228px;\">"+
"</button>");
%>
</body>
</html>
to run these files code I am using eclipse IDE, inside eclipse IDE I am able to view the 333.jpg image and able to upload other file, but when I copy the local host URL from eclipse and running the program by using chrome browser I am able to upload file but can not able to view the 333.jpg image file which is uploaded already into given path.
I want to know why that is happening and what is the solution for it?
just change message.jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload</title>
</head>
<body>
<h2>${requestScope.message}</h2>
<%# page import="java.io.File"%>
<%
String SAVE_DIR = "uploadFiles";
String appPath = request.getContextPath();
String savePath = appPath + File.separator + SAVE_DIR+ File.separator +"kala"+ File.separator;
out.write("<h3>This is the Profile Picture</h3><br><br><button type=\"submit\" name=\"img\">"+
"<img src=\""+savePath+"333.jpg\" style=\"width:304px;height:228px;\">"+
"</button>");
%>

Desktop Shortcut Creation: onClick of image link

I am using a JNI library (jshortcut-0.4-oberzalek https://github.com/jimmc/jshortcut/downloads ).
I wrote one jsp file and imported this jar and I am calling this jsp in ajax call.
i placed the library project folder, I am using WinSCP and putty.
Now I am getting the java.lang.unsatisfiedlinkerror: jshortcut not found in java.library.path
Code :DesktopCreation.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import ="net.jimmc.jshortcut.JShellLink" %>
<%# page import="javax.servlet.http.HttpServlet,javax.servlet.http.HttpServletRequest,
javax.servlet.http.HttpServletResponse" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="link" class="net.jimmc.jshortcut.JShellLink"></jsp:useBean>
<%!
JShellLink link;
String imgPath;
String iconPath="";
%>
<%
link = new JShellLink();
imgPath = JShellLink.getDirectory("") + "http://www.google.com";
iconPath="F:/WorkWorship/ShortCut/img/ico6.ico";
link.setFolder(JShellLink.getDirectory("desktop"));
link.setName("Manju");
link.setPath(imgPath);
link.setIconLocation(iconPath);
link.save();
%>
</body>
</html>
Code : Ajax
/*
* creates a new XMLHttpRequest object which is the backbone of AJAX,
* or returns false if the browser doesn't support it
*/
function getXMLHttpRequest() {
var xmlHttpReq = false;
// to create XMLHttpRequest object in non-Microsoft browsers
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
// to create XMLHttpRequest object in later versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
// to create XMLHttpRequest object in older versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
}
/*
* AJAX call starts with this function
*/
function createShortCut() {
var xmlHttpRequest = getXMLHttpRequest();
var con=confirm("Do you Wish to Crete?");
if(con){
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("GET", "DesktopCreation.jsp", true);
xmlHttpRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlHttpRequest.send(null);
alert("ShortCut Created....");
alert("Thanks for Downloading ShortCut");
}else{
alert("No thanks .....");
}
}
/*
* Returns a function that waits for the state change in XMLHttpRequest
*/
function getReadyStateHandler(xmlHttpRequest) {
// an anonymous function returned
// it listens to the XMLHttpRequest instance
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
document.getElementById("hello").innerHTML = xmlHttpRequest.responseText;
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
}
Code:Shortcut.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>SHORTCUT</title>
<script type="text/javascript" language="javascript" src="ajax.js"></script>
</head>
<body>
<h4 id="hello">Create ShortCut</h4>
<input type="image" src="F:\WorkWorship\DescktopShortCut\Dasara.jpg" width="100" height="100" onclick="createShortCut()" />
</body>
</html>
please any one can help.
Thanks in Advace

Saving selected option from combo box to file using JSP

I have a problem, I'm not sure how to save selected option to a file.
What the code looks like is:
<%# page import="java.io.PrintWriter" %>
<%# page import="java.time.LocalDateTime" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Combo box to file</title>
</head>
<body>
<%PrintWriter writer; %>
<select>
<option value="Date">
Current Date and Time
<%
writer = new PrintWriter("text.txt", "UTF-8");
writer.println(LocalDateTime.now().toString());
writer.close();
%>
</option>
<option value="Text">
Some Text
<%
writer = new PrintWriter("text.txt", "UTF-8");
writer.println("Some text");
writer.close();
%>
</option>
<option value="Integer">
An Integer
<%
writer = new PrintWriter("text.txt", "UTF-8");
writer.println(123);
writer.close();
%>
</option>
</select>
</body>
</html>
And it doesn't do anything. My guess is that the code isn't invoked but I'm very new to this, not sure how to solve this.

Display all images from relative path in jsp with spring mvc

I upload images to a folder and save relative path to database. But when i try to display all images it shows only one image (the first one) and then I get an error:
SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:636)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:214)
Any body how knows how I can fix the problem?
All kind of helps would be appreciated.
Here is the controller for reading the files:
#RequestMapping(value = "/allpictures", method = RequestMethod.GET)
public String getAllImages(ModelMap model, HttpServletRequest req, HttpServletResponse response, SecurityContextHolderAwareRequestWrapper request)
{
String name = request.getUserPrincipal().getName();
model.addAttribute("username", name);
Collection<UploadImage> images = img.showAllPictures();
for (UploadImage uploadImage : images)
{
System.out.println("name "+uploadImage.getFileName());
System.out.println("path "+uploadImage.getFilePath());
System.out.println("upload "+uploadImage);
OutputStream out;
try
{
out = response.getOutputStream();
InputStream inputStream = new FileInputStream(new File(uploadImage.getFilePath()));
byte[] buf = new byte[32 * 102400];
int nRead = 0;
while ((nRead = inputStream.read(buf)) != -1)
{
out.write(buf, 0, nRead);
}
model.addAttribute("all", uploadImage);
out.flush();
out.close();
return "allpictures";
}
catch (IOException e)
{
e.printStackTrace();
}
}
return "redirect:/index";
}
And this is the jsp code:
<%# page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4 /loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
</head>
<body>
<c:forEach var="all" items="${all}">
<img alt="pictures3" src="<%=request.getContextPath()%>/${all}" width="70" height="70">
</c:forEach>
</body>
</html>

Categories