According to this [https://stackoverflow.com/a/24264878/2382770][1] answer (it's no accepted) I try read image file from OpenShift DATA_DIR but get message in browser:
Image «http://app-name.rhcloud.com/GetImageServlet?img=681265.jpg»
can not be shown since contains errors."
#WebServlet("/GetImageServlet")
public class GetImageServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = request.getParameter("img");
String uploadFilePath = ...;
System.out.println(uploadFilePath);
byte[] imageBytes = getImageAsBytes(uploadFilePath);
response.setContentType("image/jpeg");
response.setContentLength(imageBytes.length);
response.getOutputStream().write(imageBytes);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
public byte[] getImageAsBytes (String ImageName) throws IOException {
// open image
File imgPath = new File(ImageName);
BufferedImage bufferedImage = ImageIO.read(imgPath);
// get DataBufferBytes from Raster
WritableRaster raster = bufferedImage .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
return ( data.getData() );
}
private static final long serialVersionUID = 1L;
}
Do we realy can get data from OpenShift DATA_DIR ?
The only mistake you made is that you send RAW image data (as read by ImageIO). Change the getImageAsBytes() method to read directly image data from file as they are (e.g. jpeg files contains image encoded in jpeg format) using standard FileInputStream. Alternatively, you can use 'Files.readAllBytes(..)' to read content of file.
Related
am new to servlet and jsp.. I am able to generate and export excel file from database in java swing. I wrote same code in servlet and i get 0 bytes after a prompt to download.
i cant seem to figure out what i left out.
#WebServlet(name = "excel_purchases", urlPatterns = {"/excel_purchases"})
public class excel_purchases extends HttpServlet {
PreparedStatement pst=null; ResultSet rs=null;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try (PrintWriter out = response.getWriter()) {
response.setContentType("application/octet-stream");
response.setHeader("content-disposition", "attachment; filename=purchases.xlsx");
/* TODO output your page here. You may use following sample code. */
try{
con = C3p0DataSource.getInstance().getConnection();
String sql = "select shop,item,date,id,source_name,quantity,unit,price,grand_total from purchase_print";
pst=con.prepareStatement(sql);
rs=pst.executeQuery();
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
XSSFSheet sheet = workbook.createSheet("purchases");
XSSFRow rowhead;
rowhead = sheet.createRow(0);
rowhead.createCell(0).setCellValue("Shop");
rowhead.createCell(1).setCellValue("Product");
rowhead.createCell(2).setCellValue("Date");
rowhead.createCell(3).setCellValue("Num");
rowhead.createCell(4).setCellValue("Source Name");
rowhead.createCell(5).setCellValue("Qnty");
rowhead.createCell(6).setCellValue("U/M");
rowhead.createCell(7).setCellValue("Cost Price");
rowhead.createCell(8).setCellValue("Amount");
int i = 1;
while(rs.next()){
XSSFRow row= sheet.createRow((short)i);
row.createCell(0).setCellValue(rs.getString("shop"));
row.createCell(1).setCellValue(rs.getString("item"));
row.createCell(2).setCellValue(rs.getString("date"));
row.createCell(3).setCellValue(rs.getDouble("id"));
row.createCell(4).setCellValue(rs.getString("source_name"));
row.createCell(5).setCellValue(rs.getDouble("quantity"));
row.createCell(6).setCellValue(rs.getString("unit"));
row.createCell(7).setCellValue(rs.getDouble("price"));
row.createCell(8).setCellValue(rs.getDouble("grand_total"));
i++;
}
workbook.write(response.getOutputStream());
}
}catch(SQLException | IOException e){
out.println(e);
}
response.sendRedirect("purchases_sect/purchases_search.jsp");
//set download format
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
when i click on this button in a jsp page..,
<button formaction="excel_purchases" formmethod="post">export to excel</button>
it does download but the excel file is empty. the file size is indicated as 0 bytes during download.
I'm trying to pull all images from a website and
analyze each one using AWS image recognition API. It works for some websites, however some websites return an error saying `500 server error java.lang.arrayindexoutofboundsexception index:281 size 281.
Basically I'm scraping images using jsoup and then creating an object to store the name and image URL for each image. After that, I call the API and check each image in the ArrayList. For some reason it only works for some websites.
Can someone please explain what I'm doing wrong and how to prevent this error?
#WebServlet(name = "HelloAppEngine", urlPatterns = {
"/hello"
})
public class HelloAppEngine extends HttpServlet {
static ArrayList < ResponseData > testImages = new ArrayList < > ();
static AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
public static void getimages() throws MalformedURLException, IOException {
System.out.println("getImages called" + testImages);
int index = 0;
for (ResponseData data: testImages) {
System.err.println("open stream for:" + data.getUrl());
ByteBuffer imageBytes = null;
try (InputStream inputStream = new URL(data.getUrl()).openStream()) {
System.out.println(inputStream);
imageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream));
System.out.println(imageBytes);
} catch (IOException e1) {
System.err.println(e1.getMessage());
}
//
DetectLabelsRequest request = new DetectLabelsRequest().withImage(new Image().withBytes(imageBytes)); //.withMaxLabels(10).withMinConfidence(77F);
try {
DetectLabelsResult result = rekognitionClient.detectLabels(request);
List < Label > labels = result.getLabels();
//System.out.println(labels);
//System.out.println("Detected labels for " + photo+""+labels);
for (Label label: labels) {
//loop through all labels of object
//create new responsedata object for each image
//where im getting error
if (testImages.get(index) != null) {
ResponseData d = testImages.get(index);
d.setName(label.getName());
testImages.set(index, d);
//increment for making new image url and name
index++;
System.out.println(label.getName() + ": " + label.getConfidence().toString());
}
}
//
} catch (AmazonRekognitionException e) {
System.err.println(e.getMessage());
}
}
}
private static final long serialVersionUID = 1 L;
protected static final Gson GSON = new GsonBuilder().create();
// This is just a test array
ArrayList < String > list = new ArrayList < String > ();
#Override
protected final void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/json");
String servlet = req.getServletPath();
System.setProperty("http.proxyHost", "192.168.5.1");
System.setProperty("http.proxyPort", "1080");
log("servlet:" + servlet);
if (servlet.equalsIgnoreCase("/main")) {
log("if body start");
String urlString = java.net.URLDecoder.decode(req.getParameter("url"), "UTF-8");
// Connect to website. This can be replaced with your file loading
// implementation
Document doc = Jsoup.connect(urlString).get();
// Get all img tags
Elements img = doc.getElementsByTag("img");
Elements media = doc.select("[src]");
int counter = 0;
// Loop through img tags
for (Element src: media) {
if (src.tagName().equals("img")) {
counter++;
//create reposnsedata object for each image url
ResponseData data = new ResponseData();
//set object url to image url
data.setUrl(src.attr("abs:src"));
//set data name from aws
data.setName(" ");
testImages.add(data);
// getimages();
}
if (src.tagName().equals("link[href~=.*\\.(ico|png)]")) {
System.out.println("image is logo");
}
if (src.tagName().equals("meta[itemprop=image]")) {
System.out.println("image is logosss");
}
}
}
//log("list" + testImages);
getimages();
//
// getimages();
System.err.println(GSON.toJson(testImages));
resp.getWriter().println(GSON.toJson(testImages));
}
#Override
protected final void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
You're trying to get 282nd image (index=281) from testImages but there's only 281 (index=280). You're getting each image for each label and it's possible there's more labels than images.
Try displaying the amount of both of them:
System.out.println("testImages.size() is: " + testImages.size());
System.out.println("labels.size() is: " + labels.size());
To avoid getting more images than labels try replacing this condition:
if (testImages.get(index) != null) {
with
if (index < testImages.size() && testImages.get(index) != null) {
html:
<form action="/upload" method="post" enctype="multipart/form-data">
<input name="upload" type="file">
<input type="submit" value="upload">
</form>
servlet3:
#WebServlet("/upload")
#MultipartConfig
public class UploadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadFileServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part filePart = request.getPart("upload");
String header = filePart.getHeader("Content-Disposition");
String filename = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\""));
System.out.println(filename);
InputStream in = filePart.getInputStream();
OutputStream out = new FileOutputStream("D:/temp.png");
byte[] buffer = new byte[1024];
int length = -1;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.close();
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
in this way, I can upload file successfully, but I'd like to deal it in struts2 the same way, code block below:
public void newTask() throws Exception {
Part filePart = request.getPart("file");
String header = filePart.getHeader("Content-Disposition");
String _filename = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\""));
InputStream in = filePart.getInputStream();
OutputStream out = new FileOutputStream("D://temp.png");
StreamUtils.copy(in, out);
}
but it doesn't work, I can't get anything from Part, it throw NullPointException, what should I do to change my code or it can't work in strut2 use the same way connect file with servlet3?
public class CompanyServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static org.apache.log4j.Logger log = Logger.getLogger(Company.class);
/**
* This string holds the filename of the file.
*/
String fileName = null;
Details detailsById = null;
Page page = null;
String date = null;
HttpServletRequest request = null;
/**
* This holds the bytes of the file to be written .
*/
Workbook wb = null;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
}
The class CompanyServlet is a singleton, so the member field request is shared between users. The result is that one user could see another user's data. How to avoid this problem.
Don't keep state in servlets, keep them in the session if you need to store them somewhere.
i am trying to upload file using this code :
package controle;
#WebServlet("/upload")
#MultipartConfig
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
String id;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
uploadFile(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
id = (String) request.getAttribute("id");
uploadFile(request, response);
}
private void uploadFile(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
for (Part part : request.getParts()) {
String name = part.getName();
InputStream is = request.getPart(name).getInputStream();
String fileName = getUploadedFileName(part);
FileOutputStream fos = new FileOutputStream(
"//C:/Users/achraf/workspace19/guidepro/WebContent/WEB-INF/imagesapp/profileapp"
+ fileName);
int data = 0;
while ((data = is.read()) != -1) {
fos.write(data);
}
fos.close();
is.close();
response.sendRedirect("success.jsp");
}
}
private String getFormat(String fileName) {
String format = "none";
int index = fileName.lastIndexOf(".");
if (index > 0) {
format = fileName.substring(index + 1);
format = format.toLowerCase();
}
return format;
}
private String getUploadedFileName(Part p) {
String file = "", header = "Content-Disposition";
String[] strArray = p.getHeader(header).split(";");
for (String split : strArray) {
if (split.trim().startsWith("filename")) {
file = split.substring(split.indexOf('=') + 1);
file = file.trim().replace("\"", "");
System.out.println("File name : " + file);
}
}
return file;
}
}
but when irun my application i get this error message:
java.io.FileNotFoundException: C:\Users\achraf\workspace19\guidepro\WebContent\WEB-INF\imagesapp\profileapp (Accès refusé)
java.io.FileOutputStream.open(Native Method)
java.io.FileOutputStream.<init>(Unknown Source)
java.io.FileOutputStream.<init>(Unknown Source)
controle.FileUploadServlet.uploadFile(FileUploadServlet.java:45)
controle.FileUploadServlet.doPost(FileUploadServlet.java:31)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
what went wrong????
Make sure there is a folder by the name imagesapp under the WEB-INF and as you have
//C:/Users/achraf/workspace19/guidepro/WebContent/WEB-INF/imagesapp/profileapp"
which means it will append the fileName to profileapp and store it in imagesapp.But if you are assuming that the file will be kept under profileapp then just put a slash atfer it like this
C:/Users/achraf/workspace19/guidepro/WebContent/WEB-INF/imagesapp/profileapp/"
In uploadFile method:
String name = part.getName();
InputStream is = request.getPart(name).getInputStream();
You already has the part to get the input stream and are using getPart(name) to get the same instance part above.
I will not recommend to get the input stream to write after to a file with some output stream.
Instead if it do the following:
String fileName = part.getHeader("content-disposition").replaceAll(".+filename=\"(.+)\"", "$1");
String fileFormat = fileName.replaceAll(".+[.](.+)$", "$1");
part.write("//C:/Users/achraf/workspace19/guidepro/WebContent/WEB-INF/imagesapp/profileapp/" + filename);
note here:
"//C:/Users/achraf/workspace19/guidepro/WebContent/WEB-INF/imagesapp/profileapp"
+ fileName
is what you did. The final / is missing in profileapp.
The message error throws:
java.io.FileNotFoundException: C:\Users\achraf\workspace19\guidepro\WebContent\WEB-INF\imagesapp\profileapp
profileapp is a folder. The message shows that your method return an empty string defined as "" at the begin of the method. If your method returns "SOME_STRING", you will see the following message error if the folder imagesapp doesn't exists:
java.io.FileNotFoundException: C:\Users\achraf\workspace19\guidepro\WebContent\WEB-INF\imagesapp\profileappSOME_STRING
Otherwise you will create the profileappSOME_STRING file inside imagesapp folder.
If your profileapp folder doesn't exists, you would create the file profileapp inside imagesapp folder without exception. Not that you had an Access refuse. You are trying to write the content in a folder as a file.