I want to download a file stored in system directory but when downloading the file in jsf page I get it empty.
This is my xhtml page :
<h:form>
<h:commandButton value="Download" action="#{helloBean.downloadFile}" />
</h:form>
and my managed bean :
#ManagedBean
#SessionScoped
public class HelloBean {
public void downloadFile() {
File file = new File("C:\\data\\contacts.doc");
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setHeader("Content-Disposition", "attachment;filename=contacts.doc");
response.setContentLength((int) file.length());
ServletOutputStream out = null;
try {
FileInputStream input = new FileInputStream(file);
byte[] buffer = new byte[1024];
out = response.getOutputStream();
int i = 0;
while ((i = input.read(buffer)) != -1) {
out.write(buffer);
out.flush();
}
FacesContext.getCurrentInstance().getResponseComplete();
} catch (IOException err) {
err.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException err) {
err.printStackTrace();
}
}
}
}
so How to solve it? Thanks in advance.
I think this code solve your problem.
public void download() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) context
.getExternalContext().getResponse();
File file = new File(filePath);
if (!file.exists()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType("application/octet-stream");
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment;filename=\""
+ file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(file),
DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(),
DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
input.close();
output.close();
}
context.responseComplete();
}
Related
Fortify find "Unreleased Resource: Streams" error for my script that I've already use try with resource :
public static void zipFiles(List<FileZipObject> fileList, File outFile) throws IOException {
try (FileOutputStream fileOutputStream = new FileOutputStream(outFile);
ZipOutputStream zipOut = new ZipOutputStream(fileOutputStream)) {
for (FileZipObject fileZipObject : fileList) {
try (FileInputStream fis = new FileInputStream(fileZipObject.getFilePath())) { // <------ This line
ZipEntry zipEntry = new ZipEntry(genEntryName(fileZipObject.getFileName()));
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
}
}
}
}
Please help me to fix this problem
public static void zipFiles(List<FileZipObject> fileList, File outFile) throws IOException {
FileOutputStream fileOutputStream = null;
ZipOutputStream zipOut = null;
try {
fileOutputStream = new FileOutputStream(outFile);
zipOut = new ZipOutputStream(fileOutputStream);
for (FileZipObject fileZipObject : fileList) {
FileInputStream fis = null;
try {
fis = new FileInputStream(fileZipObject.getFilePath());
ZipEntry zipEntry = new ZipEntry(genEntryName(fileZipObject.getFileName()));
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
} finally {
if (fis != null) {
fis.close();
}
}
}
} finally {
if (zipOut != null) {
zipOut.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
}
}
I'm trying to make a connection to a URL which displays some data in plain text on a webpage (it's a block of text in between <pre> tags). Whenever a character with a character with a special character is passed through (for example é or ì) it displays a question mark instead of the character a �
is displayed. I've tried using this but that didn't change much. I can't read the page per line so I'm pretty much stuck here.
Here is my code:
try
{
// Open the connection
NetworkManager networkManager = NetworkManager.getInstance();
networkManager.addErrorListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
NetworkEvent n = (NetworkEvent) evt;
n.getError().printStackTrace();
success = false;
}
});
ConnectionRequest request = new ConnectionRequest()
{
{
setTimeout(40000);
}
#Override
protected void readResponse(InputStream input) throws IOException
{
InputStreamReader inputStreamReader = new InputStreamReader(input, "UTF-8");
int chr;
buffer = new StringBuilder();
//reading the answer
while ((chr = inputStreamReader.read()) != -1)
{
System.out.println("Append the character " + (char) chr);
buffer.append((char) chr);
}
response = buffer.toString();
response = response.trim();
data = new byte[buffer.length()];
int tmpCounter = buffer.length();
counter = 0;
while (counter != buffer.length())
{
for (int i = 0; i < tmpCounter; i++)
{
data[counter + i] = (byte) buffer.charAt(i);
}
counter += tmpCounter;
}
process(data);
dataEvent.setDataAvailable();
}
#Override
protected void handleException(Exception err)
{
success = false;
dataEvent.setDataAvailable();
}
};
request.setUrl(url);
request.setPost(false);
networkManager.addToQueue(request);
}
catch (Exception x)
{
x.printStackTrace();
}
Turns out the actual response didn't respond using UTF-8 the characters were just readable in my browser. I fixed it by specifying the response characters should be UTF-8
I am using this code to upload an image. It works on emulator but always fail on Android device (OS 6.0)
My code is
`private void uploadImage3(final String imagePath, String id){
final Hashtable htArg = new Hashtable();
htArg.put("pk1value", id);
htArg.put("pk2value", "");
htArg.put("pk3value", "");
htArg.put("datatype", "6");
htArg.put("module", "");
htArg.put("action", "");
try {
htArg.put("thefile", FileSystemStorage.getInstance().openInputStream(imagePath));
} catch (IOException ex) {
Log.p("imgRequest.Error = " + ex.toString());
}
htArg.put("submit", "Submit");
final String boundary = "-----------------------------0123456789012";
MultipartRequest request = new MultipartRequest(){
#Override
protected void buildRequestBody(OutputStream os) throws IOException {
Writer writer = null;
writer = new OutputStreamWriter(os, "UTF-8");
String CRLF = "\r\n";
boolean canFlushStream = true;
Enumeration e = htArg.keys();
while(e.hasMoreElements()) {
if (shouldStop()) {
break;
}
String key = (String)e.nextElement();
Object value = htArg.get(key);
writer.write("--");
writer.write(boundary);
writer.write(CRLF);
if(value instanceof String) {
writer.write("Content-Disposition: form-data; name=\""+key+"\"");
writer.write(CRLF);
writer.write(CRLF);
writer.write(CRLF);
if(canFlushStream){
writer.flush();
}
writer.write(Util.encodeBody((String)value));
if(canFlushStream){
writer.flush();
}
}else {
writer.write("Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + key +"\"");
writer.write(CRLF);
writer.write("Content-Type: ");
writer.write("image/jpeg");
writer.write(CRLF);
writer.write("Content-Transfer-Encoding: binary");
writer.write(CRLF);
writer.write(CRLF);
if(canFlushStream){
writer.flush();
}
InputStream i;
if (value instanceof InputStream) {
i = (InputStream)value;
byte[] buffer = new byte[8192];
int s = i.read(buffer);
while(s > -1) {
os.write(buffer, 0, s);
if(canFlushStream){
writer.flush();
}
s = i.read(buffer);
}
// (when passed by stream, leave for caller to clean up).
if (!(value instanceof InputStream)) {
Util.cleanup(i);
}
} else {
os.write((byte[])value);
}
value = null;
if(canFlushStream){
writer.flush();
}
}
writer.write(CRLF);
if(canFlushStream){
writer.flush();
}
}
writer.write("--" + boundary + "--");
writer.write(CRLF);
if(canFlushStream){
writer.flush();
}
writer.close();
}
#Override
protected void readResponse(InputStream input) {
try {
Result result = Result.fromContent(input, Result.XML);
Log.p("imgRequest response: " + result.toString());
} catch (Exception ex) {
Log.p("imgRequest.Error = " + ex.toString());
ex.printStackTrace();
}
}
#Override
protected void handleErrorResponseCode(int code, String message) {
Log.p("handleErrorResponseCode = "+code + ":" + message);
}
#Override
protected void handleException(Exception err) {
Log.p("handleException = "+err.toString());
err.printStackTrace();
}
};
String theURL = Application.getCurrentConnection().get("URL").toString() + "/W1Servlet";
request.setUrl(theURL+"/uploadfiledebug");
request.setBoundary(boundary);
request.setPost(true);
try {
//need to keep this code as it will calculate file size internally
// and also have to add thefile separately in myArgHashTable
request.addData("thefile", imagePath, "image/jpeg");
request.setFilename("thefile", "img.jpeg");
} catch (Exception ex) {
}
InfiniteProgress prog = new InfiniteProgress();
Dialog dlg = prog.showInifiniteBlocking();
request.setDisposeOnCompletion(dlg);
NetworkManager.getInstance().addToQueueAndWait(request);
}`
The traced error on real device is,
`java.net.ProtocolException: exceeded content-length limit of 11076 bytes
at com.android.okhttp.internal.http.RetryableSink.write(RetryableSink.java:58)
at com.android.okhttp.okio.RealBufferedSink.close(RealBufferedSink.java:234)
at com.android.okhttp.okio.RealBufferedSink$1.close(RealBufferedSink.java:209)
at com.codename1.impl.CodenameOneImplementation.cleanup(CodenameOneImplementation.java:4385)
at com.codename1.impl.android.AndroidImplementation.cleanup(AndroidImplementation.java:4579)
at com.codename1.io.Util.cleanup(Util.java:149)
at com.codename1.io.BufferedOutputStream.close(BufferedOutputStream.java:287)
at com.codename1.impl.CodenameOneImplementation.cleanup(CodenameOneImplementation.java:4385)
at com.codename1.impl.android.AndroidImplementation.cleanup(AndroidImplementation.java:4579)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:804)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:282)
at com.codename1.impl.CodenameOneThread$1.run(CodenameOneThread.java:60)
at java.lang.Thread.run(Thread.java:818)`
I am not sure what I am missing.
Please someone can help me.
Thanks
Updated Code
`private void uploadImage4(final String imagePath, String id){
MultipartRequest request = new MultipartRequest(){
#Override
protected void readResponse(InputStream input) throws IOException {
try {
Result result = Result.fromContent(input, Result.XML);
if(isDebugOn){
Application.writeInDebugFile(debugFileName,
"result.toString(): "+ result.toString());
}
Log.p("imgRequest response: " + result.toString());
} catch (Exception ex) {
Log.p("imgRequest.Error = " + ex.toString());
ex.printStackTrace();
if(isDebugOn){
Application.writeInDebugFile(debugFileName,
"readResponse.Exception: "+ex.toString());
}
}
}
};
String theURL = Application.getCurrentConnection().get("URL").toString() + "/W1Servlet";
request.setUrl(theURL+"/uploadfiledebug");
request.addArgument("entityname", "RCV_HEADERS");
request.addArgument("category", "37");
request.addArgument("description", "Uploaded by More4Apps Mobile App");
request.addArgument("pk1value", id);//this is used as a primary key
request.addArgument("pk2value", "");
request.addArgument("pk3value", "");
request.addArgument("datatype", "6");
request.addArgument("module", "");
request.addArgument("action", "");
request.addArgument("submit", "Submit");
try {
//add the data image
request.addData("thefile", imagePath, "image/jpeg");
request.setFilename("thefile", "img.jpeg");
} catch (IOException ex) {
Log.p("Error:"+ ex.toString());
}
request.setPriority(ConnectionRequest.PRIORITY_CRITICAL);
NetworkManager.getInstance().addToQueue(request);
}`
And new error is:
`<ERROR_MESSAGE>IO Error:com.more4apps.mobile.ActionUploadFileoracle.ord.im.OrdHttpUploadException: IMW-00106: the end-of-headers delimiter (CR-LF) was not present
IMW-00112: additional error information: Content-Type: text/plain; charset=UTF-8IMW-00106: the end-of-headers delimiter (CR-LF) was not present
IMW-00112: additional error information: Content-Type: text/plain; charset=UTF-8
oracle.ord.im.OrdMultipartParser.doParse(OrdMultipartParser.java:312)
oracle.ord.im.OrdMultipartParser.parseFormData(OrdMultipartParser.java:150)
oracle.ord.im.OrdHttpUploadFormData.parseFormData(OrdHttpUploadFormData.java:532)
com.more4apps.mobile.ActionUploadFile.performAction(ActionUploadFile.java:39)
com.more4apps.mobile.W1Servlet.processAction(W1Servlet.java:449)
com.more4apps.mobile.W1Servlet.doPost(W1Servlet.java:248)
javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:64)
oracle.apps.jtf.base.session.ReleaseResFilter.doFilter(ReleaseResFilter.java:26)
com.evermind.server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:15)
oracle.apps.fnd.security.AppsServletFilter.doFilter(AppsServletFilter.java:318)
com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:642)
com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:391)
com.evermind.server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:908)
com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:458)
com.evermind.server.http.AJPRequestHandler.run(AJPRequestHandler.java:313)
com.evermind.server.http.AJPRequestHandler.run(AJPRequestHandler.java:199)
oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:260)
com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
java.lang.Thread.run(Thread.java:682)</ERROR_MESSAGE>`
If you override buildRequestBody in a multipart request you effectively disable its functionality...
All of that code is incorrect and shouldn't be there. Multipart will work for large files by default.
I have problem with loading image from database to jsp view. It looks like action are execute but stop in middle.
I log when execute() method start and when its end. In log file i can see start this method but there are no end.
I have action:
public class ShowImageAction extends BaseAction {
private static final long serialVersionUID = 1L;
private static final Log LOG = LogFactory.getLog(ShowImageAction.class);
private int id;
public String execute() {
LOG.info("Enter execute()");
MessageBean messageBean = (MessageBean) sessionParameters
.get(SessionParameters.BANNER_EDIT);
IFiles filesEJB = EJBLocator.getFiles();
if (messageBean != null) {
id = messageBean.getBannerId();
}
FileBean file = filesEJB.file(id);
LOG.info("Id = " + id);
if (file != null) {
byte[] bytes = null;
try {
LOG.info("File: name = " + file.getName() + ". type = "
+ file.getType());
if (file.getImage() != null) {
bytes = FileUtils.readFileToByteArray(file.getImage());
HttpServletResponse response = ServletActionContext
.getResponse();
response.setContentType(file.getType());
OutputStream out = response.getOutputStream();
out.write(bytes);
out.close();
} else {
LOG.info("execute(): Nie udało się pobrać pliku z bazy danych!");
}
} catch (IOException e) {
LOG.error(e);
}
} else {
LOG.info("execute(): Nie udało się pobrać pliku z bazy danych!");
}
LOG.info("Exit execute()");
return NONE;
}
jsp:
<div class="OneFilteringRow">
Podgląd<br />
<img src="/ebok-bm/ShowImageAction" alt="Podgląd banera" />
</div>
struts.xml
<action name="ShowImageAction"
class="pl.bm.action.content.ShowImageAction">
</action>
Problem was in:
FileBean file = filesEJB.file(id);
I get bytes from database and try to save it to tmpFile. Now I get bytes and writes them to a temporary file and immediately transmit it to the action and everything is ok.
Now I have:
FileBean file = filesEJB.file(id);
LOG.info("Id = " + id);
if (file != null) {
byte[] bytes = null;
try {
LOG.info("File: name = " + file.getName() + ". type = "
+ file.getType());
if (file.getImage() != null) {
**bytes = file.getImage();**
HttpServletResponse response = ServletActionContext
.getResponse();
response.setContentType(file.getType());
OutputStream out = response.getOutputStream();
out.write(bytes);
out.close();
} else {
LOG.info("execute(): Nie udało się pobrać pliku z bazy danych!");
}
} catch (IOException e) {
LOG.error(e);
}
}
Switch to your own result implements Result class and write output here.Other in struts.xmlaction result type specified own with approx mate parameters.
refer:generate own image as action result
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to save an image into photo gallery using j2me
I am working on an application in which i want to download an image from internet and save it to photo gallery of every mobile. Please provide me suggestion.
Thanks,
private void downloadImage(String folder, String photoName, String url) throws IOException
{
byte[] rawImg = null;
try
{
String imageData = getDataFromUrl(url);
rawImg = imageData.getBytes();
putPhotoToPhone(rawImg, folder, photoName);
}
catch(Exception e1) {
e1.printStackTrace();
}
}
private String getDataFromUrl(String url) throws IOException {
StringBuffer b = new StringBuffer();
InputStream is = null;
HttpConnection c = null;
long len = 0 ;
int ch = 0;
c = (HttpConnection)Connector.open(url);
is = c.openInputStream();
len = c.getLength();
if( len != -1)
{
for(int i =0 ; i < len ; i++ )
{
if((ch = is.read()) != -1)
{
b.append((char) ch);
}
}
}
else
{
while ((ch = is.read()) != -1)
{
len = is.available() ;
b.append((char)ch);
}
}
is.close();
c.close();
return b.toString();
}
private void putPhotoToPhone(byte[] rawImg, String photoDir, String imageName)
{
FileConnection fcDir, fcFile;
String pRoot = "Phone:/";
OutputStream os;
if (rawImg != null)
{
try
{
fcDir = (FileConnection) Connector.open("file:///"+pRoot+photoDir+"/", Connector.READ_WRITE);
if (!fcDir.exists())
fcDir.mkdir();
fcFile = (FileConnection) Connector.open("file:///"+pRoot+photoDir+"/"+imageName, Connector.READ_WRITE);
if (fcFile.exists())
fcFile.delete();
fcFile.create();
os = fcFile.openOutputStream();
os.write(rawImg);
os.flush();
os.close();
fcFile.close();
fcDir.close();
}
catch (Exception e) {}
}
}