How to use excel to pdf REST api provided by ConvertApi? - java

I am planning to use, excel to pdf api (REST) in my java code provided by ConvertApi.
please share the code snippet to be used for the same.
Thanks in advance.

Please try the code below
Library
package com.excel2pdfconvert.example;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
public class Xls2PDFConvertBean {
private File file;
private String outputDir;
private String filesize;
private String filename;
public void setOutputDir(String outputDir) {
this.outputDir = outputDir;
}
public void setExcelFile(File file) {
this.file = file;
}
public String getFilesize() {
return filesize;
}
public String getFilename() {
return filename;
}
/**
* Run request for page conversion
* #return resultcode "0" in error, "1" in success
* #throws UnsupportedEncodingException
*/
public String doRequest() throws UnsupportedEncodingException{
String resultcode = "0";
HttpPost httppost = new HttpPost("https://v2.convertapi.com/convert/xlsx/to/pdf");
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
// For File parameters
entity.addPart("file", new FileBody(file, "binary/octet-stream"));
httppost.setEntity( entity );
HttpClient httpclient = new DefaultHttpClient();
try {
HttpResponse response = httpclient.execute(httppost);
Header rcHeader = response.getFirstHeader("result");
if(rcHeader != null){
resultcode = rcHeader.getValue();
if("True".equals(resultcode)){
filesize = response.getFirstHeader("filesize").getValue();
filename = response.getFirstHeader("OutputFileName").getValue();
HttpEntity hentity = response.getEntity();
if(hentity != null){
InputStream istream = hentity.getContent();
File file = new File(outputDir+File.separator+filename);
FileOutputStream ostream = new FileOutputStream(file);
byte[] b = new byte[1024];
int num = 0;
while( (num = istream.read(b, 0, b.length)) > 0)
ostream.write(b, 0, num);
istream.close();
ostream.flush();
ostream.close();
}
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return resultcode;
}
}
The web page
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%# page import="com.excel2pdfconvert.example.Xls2PDFConvertBean" %>
<%# page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%# page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>
<%# page import="java.util.*" %>
<%# page import="java.io.File" %>
<%# page import="org.apache.commons.fileupload.FileItem" %>
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
Excel2Pdf Api Demo
</title>
<script type="text/javascript">
function BeforeConvert() {
document.getElementById('LabelMessage').innerHTML = 'Please wait...';
document.getElementById('HyperLinkFile').innerHTML = '';
document.getElementById('LabelFileSize').innerHTML = '';
document.getElementById('LabelFileName').innerHTML = '';
}
</script>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<div>
<h1>Excel2Pdf Api Demo</h1>
Upload Excel file:
<input type="file" name="excel" />
<input type="submit" name="btnConvert" value="Convert" onclick="BeforeConvert();" id="btnConvert" />
<br />
<br />
<% if(ServletFileUpload.isMultipartContent(request)){
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request);
File uploadedFile = null;
String[] allowedExt = {"csv", "xls", "xlsx", "xlsb", "xlt", "xltx"};
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (! item.isFormField()) {
//Check for valid excel extensions
String fileName = item.getName();
boolean isValid = false;
for(String ext : allowedExt){
if(fileName.contains(ext)){
isValid = true;
break;
}
}
if(isValid){
uploadedFile = new File(application.getRealPath("/") + "/" + fileName);
item.write(uploadedFile);
}
}
}
if(uploadedFile == null){
out.println("<div>Please upload file in following format: csv, xls, xlsx, xlsb, xlt, xltx");
}else{
Xls2PDFConvertBean xls2pdf = new Xls2PDFConvertBean();
xls2pdf.setOutputDir(application.getRealPath("/"));
xls2pdf.setExcelFile(uploadedFile);
String resultcode = xls2pdf.doRequest();
//Remove uploaded file after conversion
uploadedFile.delete();
if(resultcode == null || "False".equals(resultcode)){
out.println("<div>Can not convert file</div>");
}else{
%>
<span id="LabelMessage">Conversion successful </span>
<br />
<a id="HyperLinkFile" href="<%= xls2pdf.getFilename() %>" >Click here to open file </a>
<br />
<span id="LabelFileSize">File size: <%= xls2pdf.getFilesize() %></span>
<br />
<span id="LabelFileName">File name: <%= xls2pdf.getFilename() %></span>
<%
}
}
}else{
%>
<span id="LabelMessage"></span>
<%
}
%>
</div>
</form>
</body>
</html>

Related

How to insert and retrieve image database using jsp/Servlet?

I have got a Form Page index.jsp :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<style>
fieldset
{
width: 70px;
}
</style>
</head>
<body>
<form action="Upload" method="post" enctype="multipart/form-data">
<fieldset>
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Select Photo</td>
<td><input type="file" name="photo"></td>
</tr>
<td><input type="submit" value="Upload"></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
MyServlet Page Upload.java:
import java.sql.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.DriverManager;
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(name = "Upload", urlPatterns = {"/Upload"})
#MultipartConfig(maxFileSize = 169999999) // upload file's size up to 16MB
public class Upload extends HttpServlet
{
private static final long serialVersionUID = 1L;
PrintWriter out;
InputStream inputStream = null;
int allField = 0;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try
{
out = response.getWriter();
String name=request.getParameter("name");
Part filePart = request.getPart("photo");
if (filePart != null)
{
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","root")
PreparedStatement ps = con.prepareStatement("insert into PhotoDetails(Name,Images)values(?,?)");
ps.setString(1,name);
ps.setBlob(2,inputStream);
ps.executeUpdate();
out.println("Image Inserted");
}
catch(Exception e)
{
out.println(e);
}
}
}
I am using mysql database and here is my table:
create table PhotoDetails
(
Name varchar(100),
Images blob
)
After filling all the form and when I click on the Update button then I get this error :
HTTP Status 500 - Servlet execution threw an exception
How could I resolve this problem?
This is the best way to show image in jsp file.
Just create showLogo.jsp
and include where ever you want it.
<%# page trimDirectiveWhitespaces="true" %>
<%# page import="java.sql.*,java.io.*,org.apache.struts2.ServletActionContext"%>
<%# page language="java" import="java.util.*, com.abc.util.dbutil.*,javax.servlet.http.HttpServletRequest" %>
<%
try{
InputStream sImage;
ResultSet resultSet = null;
PreparedStatement pstmt = null;
DBConnection dbConnection= null;
dbConnection= new DBConnection();
Connection con = null;
con= dbConnection.getConnection();
ServletInputStream sInIm = null;
Statement st=con.createStatement();
String company_id = request.getParameter("company_id");
resultSet=st.executeQuery("select logo from company where company_id='" + company_id + "'");
if(resultSet.next()){
byte[] bytearray = new byte[1048576];
int size=0;
sImage = resultSet.getBinaryStream(1);
response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1){
response.getOutputStream().write(bytearray,0,size);
}
response.getOutputStream().flush();
response.getOutputStream().close();
}
con.close();
}
catch(Exception ex){
}
%>
I am getting it like this.
/company/showLogo.jsp?company_id=" id="blah_s" class="logo-small">
Get image from file to FileInputStream
FileInputStream fs = null;
try {
fs = new FileInputStream(getUserImage());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
.................
ps.setBinaryStream(8, fs, fs.available());
insert into table(logo) values (?)
This is for mysql with blob column.

How to convert absolute path to a relative path so that it can be referenced from an img tag? java web

Creating a web application that lets users upload images.
The code works but having trouble understanding how to get the images in a relative path so that it can be referenced from an img src="" tag?
So far the code takes the multipart request and stores the file in an absolute path on server but this cannot be referenced from an < img > tag..
Any ideas on how to go about this?
UploadFile.java (servlet)
package userServlets;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
#MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50) // 50MB
#WebServlet("/UploadFile")
public class UploadFile extends HttpServlet {
private boolean isMultipart;
private static final long serialVersionUID = 1L;
public UploadFile() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// get session
HttpSession session = request.getSession();
// get the save location for files that user uploads to web app
String appPath = request.getServletContext().getRealPath("/uploads");
// get the name of the currently logged in user
String user = session.getAttribute("loggedInUser").toString();
// create the user's own folder in uploads folder of server.
String directory = appPath + File.separator + user;
File fileSaveDir = new File(directory);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
// get the path of the users folder location as a file
File uploads = new File(
request.getSession().getServletContext().getRealPath("/uploads" + File.separator + user));
// Check if request is multipart, if not, sends user back to uplaod page
// (test.jsp)
isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
RequestDispatcher rd = request.getRequestDispatcher("test.jsp");
rd.forward(request, response);
}
// Suspicious looking stuff not too sure of but works i guess :/
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(uploads);
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// iterates over form's fields
for (FileItem item : formItems) {
// processes only fields that are not form fields
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
long sizeInBytes = item.getSize();
String filePath = uploads + File.separator + fileName;
File storeFile = new File(filePath);
// saves the file on disk
item.write(storeFile);
request.setAttribute("message", "Upload has been done successfully!");
request.setAttribute("filename", fileName);
// *STORE THIS IN DATABASE
request.setAttribute("filepath", filePath);
request.setAttribute("filesize", sizeInBytes);
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
request.setAttribute("directory", directory);
RequestDispatcher rd = request.getRequestDispatcher("test.jsp");
rd.forward(request, response);
}
}
}
test.jsp (upload form)
<%# 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>Insert title here</title>
</head>
<body>
<div class="jumbotron">
<div class="container">
<form method="post" enctype="multipart/form-data" action="UploadFile">
<input type="text" name="description" /> <input type="file"
name="file" /> <input type="submit" />
</form>
</div>
</div>
<h1>"${directory}"</h1>
<h1>"${message}"</h1>
<h1>"${filepath}"</h1>
<h1>"${filename}"</h1>
<h1>"${filetype}"</h1>
<h1>"${filesize}"</h1>
<img src="${filepath}">
<hr />
<div class="jumbotron">
<img alt="" src="hmmmmmm">
</div>
</body>
</html>
Figured it out after reading this link
If you have full control over the images folder, then just drop the
folder with all images, e.g. /images directly in servletcontainer's
deploy folder, such as the /webapps folder in case of Tomcat and
/domains/domain1/applications folder in case of GlassFish. No further
configuration is necessary.
literally drag and drop the file into the web application folder in your ide.
then you do this

Jsp doesn't show swf File

I have a Webproject with JavaEE (Tomcat, Jsp, Servlets)
I want to Show a SWF in my Jsp Page (game.jsp). For doing this i Need a Servlet, which is this:
package src;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.SystemEnviroement;
/**
* Servlet implementation class ImageServlet
*/
#WebServlet("/ImageServlet")
public class ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ImageServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ServletContext sc = getServletContext();
String imageName = request.getParameter("imageName");
SystemEnviroement env = new SystemEnviroement();
String filename = env.gameFolder + "/" + imageName;
// Get the MIME type of the image
String mimeType = sc.getMimeType(filename);
if (mimeType == null) {
// sc.log("Could not get MIME type of " + filename);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Set content type
response.setContentType(mimeType);
// Set content size
File file = new File(filename);
response.setContentLength((int) file.length());
// Open the file and output streams
FileInputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
in.close();
out.close();
}
}
My game.jsp is this:
<%# page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%# page import="util.*"%>
<%# page import="constants.*"%>
<%# page import="java.io.IOException"%>
<!DOCTYPE html>
<html >
<head>
<jsp:include page='header.jsp'/>
<%
String gamename = (String) request.getAttribute("javax.servlet.forward.request_uri");
int index_name = gamename.lastIndexOf("/");
gamename = gamename.substring(index_name+1,gamename.length());
%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body style="background-color:#630592;
background-repeat:no-repeat;"
>
<div class="body">
<%
try {
//SystemEnviroment wird im Konstruktor gesetzt
SystemEnviroement en = new SystemEnviroement();
String datei = en.imageViewPath + gamename +".swf";
%>
<div class=gameswf>
<a> <embed src='<%=datei %>' > </embed> </a>
</div>
<%
}catch(IOException e){
e.printStackTrace();
}
%>
</div>
</body>
</html>
So i have debugged my Project, all thinks Looks well. But after calling the Servlet, the game.jsp doesn't Show the SWF File.
The htmltext(sourcecode) also Looks well, but the game.jsp doesn't Show the SWF File:
<div class=gameswf>
<a> <embed src='http://localhost:8080/Game/imageView?imageName=3-pandas.swf'> </embed> </a>
</div>
If i call this URL in my running web Project "http://localhost:8080/Game/imageView?imageName=3-pandas.swf", i can sell the SWF File and all is fine.
Do you have any idea why the jsp page doesn't Show my SWF File. If i go to the Internet explorer add ons, i can also see that Shockwave Flash Object is loading.
Thanks for helping !
This is the Image from ie 11 network monitoring feature from developer Tools:
I suggest you to create an html file (with html extension) and write the code you expect from the jsp to generate.
Once you make the swf work in html file, it will be a piece of cake to develop the proper jsp code in order to generate that html file.

Servlet Image Upload - Cannot get other form fields

I am having a problem with my image upload code. When I try to use request.getParameter("title") from the form, the upload doesn't succeed. But when I remove the request.getParameter("title"), it works.
In short, how can I access other form fields? I want to store their values somewhere.
Here is my form:
<%# 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>
<div>
<form action="ImageUpload" method="POST" enctype="multipart/form-data"><br>
Title:<input type="text" name="title" id="title" /><br>
Reporter:<input type="text" name="reporter" id="reporter"><br>
Image:<input type="file" name="image" id="image" /><br>
<input type="submit" value="Upload">
</form>
</div>
</body>
</html>
The Upload Servlet:
package socialnewsreloaded.upload;
import java.io.IOException;
import java.io.InputStream;
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 org.apache.tomcat.util.http.fileupload.FileItemIterator;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.servlet.*;
/**
* Servlet implementation class ImageUpload
*/
#WebServlet("/ImageUpload")
#MultipartConfig
public class ImageUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
String title = request.getParameter("title");
response.getWriter().print(title);
if (isMultiPart) {
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator iterate = upload.getItemIterator(request);
while (iterate.hasNext()) {
FileItemStream item = iterate.next();
if (item.isFormField()) {
String fieldName = item.getFieldName();
InputStream inStream = item.openStream();
byte[] b = new byte[inStream.available()];
inStream.read(b);
String value = new String(b);
//response.getWriter().print(fieldName+":"+value);
} else {
String path = "C:/uploads";
if (FileUpload.processFile(path, item)) {
response.getWriter().print(
"File Uploaded Successfully");
} else {
response.getWriter().print(
"Error Uploading File !!");
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}
}
FileUpload Class:
package socialnewsreloaded.upload;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
public class FileUpload {
public static boolean processFile(String path, FileItemStream stream)
throws IOException {
File file = new File(path + File.separator + "images");
if (!file.exists()) {
file.mkdir();
}
File savedFile = new File(file.getAbsolutePath() + File.separator
+ stream.getName());
try {
FileOutputStream outStream = new FileOutputStream(savedFile);
InputStream inStream = stream.openStream();
int i = 0;
byte[] b = new byte[1024];
while((i=inStream.read(b))!=-1){
outStream.write(b, 0, i);
}
outStream.flush();
outStream.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
}
It's the printing, not the getParameter("title"). You shouldn't produce any output until you've consumed all the input.

Google App Engine & Java : upload files into the blobstore

I would like to know if it's possible to upload a file into the gae blobstore without using servlets, is it also possible to get the inserted blobkey once the insert is done? this is the code I have done so far:
public Upload(Blob picture) {
HTTPResponse fetch = null;
try {
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
URLFetchService urlfetch = URLFetchServiceFactory.getURLFetchService();
String uploadUrl = blobstoreService.createUploadUrl("/upload");
URL url = new URL(uploadUrl);
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(picture.getBytes());
try {
urlfetch.fetch(request);
} catch (IOException ex) {
java.util.logging.Logger.getLogger(Outfit.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (MalformedURLException ex) {
java.util.logging.Logger.getLogger(Outfit.class.getName()).log(Level.SEVERE, null, ex);
}
}
There is no way to upload a file into blobstore at the momenent without using a servlet.
I suppose if you like you can use the new experimental write api of the blobstore.
The upload example in the GAE docs is pretty straight forward and would suggest sticking to it. Take a look at the Blobstore Java API Overview. There is an example in the link.
Is better with a servlet, I'll share code works perfectly for climbing and BlobKey must capture and store in datastore
.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# page import="java.util.*" %>
<%# page import="com.google.appengine.api.blobstore.BlobstoreServiceFactory" %>
<%# page import="com.google.appengine.api.blobstore.BlobstoreService" %>
<%
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
String url = blobstoreService.createUploadUrl("/upload");
%>
<!DOCTYPE html>
<html lang="en">
<body>
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 control-label">Foto</label>
<div class="col-lg-10">
<input id="file-foto-usuario" type="file" name="file-foto-usuario" onchange="UploadImage()">
<input type="hidden" class="form-control" id="foto-usuario" placeholder="Foto">
</div>
</div>
</body>
.js
function UploadImage(){
var inputFileImage = document.getElementById("file-foto-usuario");
var file = inputFileImage.files[0];
var data = new FormData();
data.append("file-foto-usuario",file);
var url = "<%=url%>";
$.ajax({
url: url,
type: 'POST',
cache : false,
data : data,
processData : false,
contentType : false,
dataType: "json",
success: function (response) {
if(response.success){
alert(response.blobKey);
}else{
alert("fail");
}
}
});
}
Upload.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
public class UploadServlet extends HttpServlet {
private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
JSONObject finalJson = new JSONObject();
Boolean success= false;
String blobid= "";
Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
BlobKey blobKey = blobs.get("file-foto-usuario");
if (blobKey == null) {
resp.sendRedirect("/");
} else {
success= true;
blobid= blobKey.getKeyString();
//resp.sendRedirect("/serve?blob-key=" + blobKey.getKeyString());
}
finalJson.put("success", success);
finalJson.put("blobKey", blobid);
resp.setCharacterEncoding("utf8");
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
out.print(finalJson);
}
}
get url image
String urlFoto = "";
BlobKey blobKey = new BlobKey(Blobkey);
ImagesService imagesService = ImagesServiceFactory.getImagesService();
try{
urlFoto = imagesService.getServingUrl(blobKey, true);
}catch (IllegalArgumentException ie){

Categories