I can generate the PDF file and save it successfully in the server, however, I don't want the newly created file to be opened on the current browser.
I am generating multiple files and mailing them at one go.
How do I stop the browser from opening the newly created file.
Response.ContentType = "application/pdf";
//Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
WholeForm.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 50f, 50f, 30f, 20f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
PdfWriter.GetInstance(pdfDoc, new FileStream("\\\\sever\\d$\\PDFs\\" + hdnFileName.Text + ".pdf", FileMode.Create));
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
pdfDoc.Dispose();
//SendEmail();
//Response.Write(pdfDoc);
//Response.End();
You are setting the content type to PDF:
Response.ContentType = "application/pdf";
And you are sending bytes to the browser using this line:
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
Remove all the lines involving the Response object, including:
Response.Cache.SetCacheability(HttpCacheability.NoCache);
The main question that remains, is: what do you want to send to the browser?
If you want to inform the end user that his PDF is being saved, you may want to show some simple HTML code with this message, for instance by using a response status code 300 (redirect). Or you don't send anything by returning the response code 204 (No Content).
Related
I tried and I face a problem when uploading images greater than 570 kb. This issue is in Xamarin Forms for android and PHP rest api. I tested the rest api separately and I have no issues there uploading 2mb files using postman.
Tried various ways also by giving some delay. I am capturing image using cross.media plugin. Then navigating to another page to upload. I wait for sometime and then click the button to upload. I am not able ascertain where the issue is.
System.IO.Stream fileStream = System.IO.File.Open(file, FileMode.Open);
byte[] data = ReadFully(fileStream);
fileStream.Close();
MultipartFormDataContent multi = new MultipartFormDataContent();
ByteArrayContent imageStream = new ByteArrayContent(data);
StringContent SequenceID = new StringContent(osequence);
imageStream.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
imageStream.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = osequence, // "screenshot.jpg", // generate this and send
Name = "avatar",
};
multi.Add(imageStream);
alertLabel.Text = "Uploading Now";
var response = await App.client.PostAsync(url, multi);
string responsestr = response.Content.ReadAsStringAsync().Result;
var retresponse = new retResponse();
bool uploadSuccess = false;
I have made the rest api to send response on error and showing the same in an alert box as below
if (responsestr != "") alertLabel.Text = responsestr.ToString();
else alertLabel.Text = alertLabel.Text + " After Upload Command ";
}
catch (Exception e)
{
}
} // private void upload(MediaFile mediaFile)
The error I get is no file sent
Please ignore the above question. The problem was solved by changing the PHP.ini max upload file size. The file size in the device was around 500 - 700 KB . don't know how it comes to 1.99 and 2 mb when uploaded. Increasing max file size solved it.
I have used the java mail API to send emails within our group. I am aware of the DataHandler objects that in turn uses FileDataSource to grab the files and attach as a multipart file. However, I am not able to use it in scala. Can anyone help me on this?
Heres my code:
def createMessage: Message = {
val properties = new Properties()
properties.put("mail.smtp.host", smtpHost)
properties.put("mail.smtp.port",smtpPort)
val session = Session.getDefaultInstance(properties, null)
return new MimeMessage(session)
}
var message: Message = null
message = createMessage
message.setFrom(new InternetAddress(from))
message.setSentDate(new Date())
message.setSubject(subject)
message.setText(content)
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to))
def sendMessage {
Transport.send(message)
}
I can use message.sefileName to set file name of the attachment, but how can I attach the actual files. For example in Java, we can achieve similar results like the following:
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(messageText);
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
FileDataSource fdatasource = new FileDataSource(file);
messageBodyPart2.setDataHandler(new DataHandler(fdatasource));
messageBodyPart2.setFileName(fdatasource.getName)
Multipart mpart = new MimeMultipart();
mpart.addBodyPart(messageBodyPart1);
mpart.addBodyPart(messageBodyPart2);
message.setContent(mpart);
I don't know this mail API, but you should be able to use a Java API the same way in Scala that you would use it in Java. If you see something like this in Java:
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(messageText);
You usually want to translate it to something like this in Scala:
val messageBodyPart1: MimeBodyPart = new MimeBodyPart()
messageBodyPart1.setText(messageText)
Just translate the Java code you have posted to Scala this way and it should work as well (or not well) as it worked in Java.
I saved a pdf file in a collection using this function:
/*** client.js ***/
// asign a change event into input tag
'change input' : function(event,template){
var file = event.target.files[0]; //assuming 1 file only
if (!file) return;
var reader = new FileReader(); //create a reader according to HTML5 File API
reader.onload = function(event){
var buffer = new Uint8Array(reader.result) // convert to binary
Meteor.call('saveFile', buffer);
}
reader.readAsArrayBuffer(file); //read the file as arraybuffer
}
/*** server.js ***/
Files = new Mongo.Collection('files');
Meteor.methods({
'saveFile': function(buffer){
Files.insert({data:buffer})
}
});
How can I read it again from the collection and provide a download link that the user can download the file as a pdf and save it on the local computer?
It depends on what the data type ends up to be on the front-end when you see that document record in your MiniMongo collection. What you want to do is to convert that Uint8Array data to a base64-encoded data URL and provide a Download PDF link after you get the data in the browser.
Meteor does not support serving files from the server out of the box, so you'll likely have to publish that file's blob via mongo->minimongo publication/subscription mechanism and then use the HTML data-uri API to get it like I've just described.
I am using something like the following to save a copy of the sent message in the user Sent folder in JavaMail. It works fine for emails with no attachment and for emails whose attachments are less than 1MB. But program stops before the code is actually executed for attachments greater than 1MB. Any idea how to deal with this one?
String host = ReadConfigPropertiesFile.getPropertyValue("server.host");
String smtpHost = ReadConfigPropertiesFile.getPropertyValue("smtp.host");
String from = "test#myserver.net";
String to = "test#myserver.net";
// Get system properties
Properties properties = System.getProperties();
// Setup smtp mail server
properties.setProperty(smtpHost, host);
properties.setProperty("mail.mime.encodeparameters", "true");
// properties.setProperty("mail.mime.decodeparameters","true");
properties.setProperty("mail.mime.encodefilename", "true");
// properties.setProperty("mail.mime.decodefilename","true");
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("Peace ", "UTF-8");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message body
messageBodyPart.setContent("Hello attachment", "text/html; charset=UTF-8");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
String[] filename = {"C:/Users/Dake/Desktop/music.mp3"};
for (int i = 0; i < filename.length; i++) {
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename[i]);
messageBodyPart.setDataHandler(new DataHandler(source));
// messageBodyPart.setFileName(filename[i]);
//messageBodyPart.setHeader("Content-Type", "text/plain; charset=UTF-8; name="+MimeUtility.encodeText(filename[i]));
// messageBodyPart.setHeader("Content-ID", filename[i]);
messageBodyPart.setFileName(MimeUtility.encodeText(filename[i], "UTF-8", null)); //encode filename
//bodyPart.setFileName(MimeUtility.encodeText(attachment.getName(), "UTF-8", null));
multipart.addBodyPart(messageBodyPart);
}
// Put parts in message
message.setContent(multipart);
//set the time
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:MM:SS");
Date date = new Date();
String sentDate = df.format(date);
Date dd = (Date) df.parse(sentDate);
message.setSentDate(date);
// Send the message
Transport.send(message);
System.out.println("Message sent...");
// Copy message to "Sent Items" folder as read
Store store = session.getStore("imap");
store.connect(host, "user", "userpwd");
Folder folder = (Folder) store.getFolder("Sent");
if (!folder.exists()) {
folder.create(Folder.HOLDS_MESSAGES);
}
folder.open(Folder.READ_WRITE);
System.out.println("appending...");
// folder.appendMessages(new Message[]{message});
try {
folder.appendMessages(new Message[]{message});
// Message[] msgs = folder.getMessages();
message.setFlag(FLAGS.Flag.RECENT, true);
} catch (Exception ignore) {
System.out.println("error processing message " + ignore.getMessage());
} finally {
store.close();
// folder.close(false);
}
System.out.println("Msg send and saved ....");
}
When I run the above code, it displays the appending.... and it stops there forever. And I am using Apache James server 3.0-beta4 as the mail server.
Is your server breaking the connection because it's taking too long to send the message to be appended? (If so, how long is it taking?)
Or is the server breaking the connection because it won't allow you to append a message that large?
Do you get any useful information from the server in the debug output?
I know this is a old question, but maybe this helps you or some others.
I guess the problem of your code is that you try to manipulate the Recent-Flag: message.setFlag(FLAGS.Flag.RECENT, true);. According to the IMAP-Standard the Recent-Flag can't be altered by clients.
I make a post request of base64 encoded data to the receipt verification address as follows (this is in C#):
var postSerializer = new JavaScriptSerializer();
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(Receipt);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
var temp = new Dictionary<string, string>();
temp.Add("receipt-data", returnValue);
string jsonReceipt = postSerializer.Serialize(temp);
request.Method = "POST";
request.ContentType = "application/json";
byte[] postBytes = System.Text.Encoding.ASCII.GetBytes(jsonReceipt);
request.ContentLength = postBytes.Length;
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(postBytes, 0, postBytes.Length);
// Close the Stream object.
dataStream.Close();
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
I'm pretty sure things are in the right format because I'm not getting any exceptions back
from the apple receipt verification endpoint. The entirety of the response I get back is
{status : -42352}
And I can't find out what this error means anywhere. Does anyone know what this means or if there's an error in my code?
Just solved the same problem. Got the solution from here: Verify receipt for in App purchase
The problem was in post encoding. When I encoded post on my server using
$receipt = json_encode(array("receipt-data" => base64_encode($receiptdata)));
I had the same -42352 status. When I used my own function for encoding on iPhone - everything worked! Magic...