upload files over https - c#-4.0

Can anyone give me a C# code snippet for this kind of file upload:
POST <BASE-URL>/documents
Content-Type: multipart/form-data; boundary=<BOUNDARY>
Transfer-Encoding: chunked
--<BOUNDARY>
Content-Disposition: form-data; name=“metadata”
Content-Type: application/json
{
“metadata” : {
“document” : {
“filename” : <filename>,
“size” : <filesize>,
“title” : <title>,
“author” : <author>
}
}
}
--<BOUNDARY>
Content-Disposition: form-data; name=“document”; filename=“<filename>”
Content-Type: <mime-type>
<File contents>
--<BOUNDARY>--
Currently I am using method shown below and I am getting status 400:Bad Request:
public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc,string accessToken)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = false;
wr.SendChunked = true;
wr.Headers.Add("Authorization", "Bearer " + accessToken);
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, file, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[256000];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
//log.Debug(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
}
I guess it is the json string part of a post header form-data that gives me the trouble... here it uses namevaluecollection...
Thanx!

Related

Resumable Upload using Google Mail APIs throwing exception: "Bad Request"

I am trying to insert mail to Google Mailbox using GMail APIs.
I want to upload mails of size more than 5 mb. So that I am using Resumable upload request.
I have used POST request first to initiate a resumable upload which gives "200 OK" response.
Post Request:
String postUrl = "https://www.googleapis.com/upload/gmail/v1/users/" + "<username>" + "/messages/send?uploadType=resumable";
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(postUrl);
httpRequest.Headers["Authorization"] = "Bearer " + f_token;// AccessToken;
httpRequest.Headers["X-Upload-Content-Type"] = "message/rfc822";
httpRequest.Headers["X-Upload-Content-Length"] = f_bytes.Length.ToString();
httpRequest.Method = "POST";
httpRequest.ContentLength = 0;
var response = (HttpWebResponse)httpRequest.GetResponse(); // 200 OK
From that response I get location URL to upload EML.
Location: https://www.googleapis.com/upload/gmail/v1/users//messages/send?uploadType=resumable&upload_id=AEnB2UqeNYKVyyQdL07RZcbenWOqY8a2NFVIsQrbA-S-vxwUXC_W4ORQtpPx1HG6tc4Indx8AvqDjwXII3F6OW0G3wsdUMUjHw
To upload EML file I used Location URL as PUT URL to create request.
putUrl = https://www.googleapis.com/upload/gmail/v1/users/<username>/messages/send?uploadType=resumable&upload_id=AEnB2UqeNYKVyyQdL07RZcbenWOqY8a2NFVIsQrbA-S-vxwUXC_W4ORQtpPx1HG6tc4Indx8AvqDjwXII3F6OW0G3wsdUMUjHw";
HttpWebRequest httpRequest1 = (HttpWebRequest)WebRequest.Create(postUrl);
httpRequest1.Method = "PUT";
httpRequest1.ContentLength = f_bytes.Length;
int EndOffset = f_bytes.Length;//5120000;5242880
httpRequest1.Headers["Content-Range"] = "bytes " + 0 + "-" + EndOffset + "/" + f_bytes.Length;
httpRequest1.ContentType = "message/rfc822";
MemoryStream stream = new MemoryStream(f_bytes);
System.IO.Stream requestStream = httpRequest1.GetRequestStream();
{
stream.CopyTo(requestStream);
requestStream.Flush();
requestStream.Close();
}
HttpWebResponse f_webResponse = (HttpWebResponse)httpRequest1.GetResponse(); //Exception
Exception :
The remote server returned an error: (400) Bad Request.
Please suggest soluion to upload eml file in a particular folder of mailbox .
I am able to send mail using resumable upload.
if (f_MailService == null)
{
bool isCreated = createMailService(ref f_MailService);
}
FileStream fs = new FileStream(#p_EMLPath, FileMode.Open,FileAccess.Read);
Create HTTPRequest for sending mail :
string postUrl = "https://www.googleapis.com/upload/gmail/v1/users/ab#edu.cloudcodes.com/messages/send?uploadType=resumable";
HttpWebRequest f_httpRequest = (HttpWebRequest)WebRequest.Create(postUrl);
f_httpRequest.Headers["X-Upload-Content-Type"] = "message/rfc822";
f_httpRequest.Headers["X-Upload-Content-Length"] = fs.Length.ToString();
f_httpRequest.Headers["Authorization"] = "Bearer " + f_token;
f_httpRequest.Method = "POST";
//f_httpRequest.ContentLength = 524288;
f_httpRequest.ContentType = "application/json; charset=UTF-8";//"message/rfc822";
f_httpRequest.ContentLength = fs.Length;
f_httpRequest.Timeout = 6000000;
f_httpRequest.SendChunked = true;
Get Response for first POST request :
try
{
using (Stream f_ObjHttpStream = f_httpRequest.GetRequestStream())
{
}
}
catch (Exception EX)
{
}
try
{
using (var response = (HttpWebResponse)f_httpRequest.GetResponse())
{
// data = ReadResponse(response);
UploadUrl = response.Headers["Location"].ToString();
}
}
catch (WebException exception)
{
using (var response = (HttpWebResponse)exception.Response)
{
// data = ReadResponse(response);
}
}
Read EML File & send chunk data to upload
byte[] Arrbyte = new byte[1024];
int ReadByte = 0;
while (fs.Length > ReadByte)
{
bool ac = false;
int ByteRead = 0;
byte[] Data = new byte[4194304];
byte[] LastData;
//Read block of bytes from stream into the byte array
// if (ReadByte == 0)
{
ByteRead = fs.Read(Data, 0, Data.Length);
}
//else
{
if ((ReadByte + Data.Length) > fs.Length)
{
//fs.Length - ReadByte-
LastData = new byte[fs.Length - ReadByte];
ByteRead = fs.Read(LastData, 0, LastData.Length);
CallPUTReq(fs.Length, LastData);
ac = true;
}
}
//f_MsgRawStr = Convert.ToBase64String(f_bytes).TrimEnd(padding).Replace('+', '-').Replace('/', '_');
ReadByte = ReadByte + ByteRead;
if (ac == false)
{
CallPUTReq(fs.Length, Data);
}
//long pos = fs.Seek(0, SeekOrigin.Current );
//fs.Position = ReadByte;
}
private void CallPUTReq(long p_lenth, byte[] Arrbyte)
{
try
{
String postUrl = UploadUrl; //"https://www.googleapis.com/upload/gmail/v1/users/ab#edu.cloudcodes.com/messages/send?uploadType=resumable&upload_id=AEnB2UqZNtZVwWulAOhAVoFp-pZ-vTMcIXOpt_0dH_6jJecpm2Y1MNOGkE6JoDb0kn9Dt4yuHHMZWR--dBncxWQkZctF9h6jiPSL5uJDKeYE9Ut1c7-fImc";
int EndOffset = 0;
HttpWebRequest httpRequest1 = (HttpWebRequest)WebRequest.Create(postUrl);
httpRequest1.Method = "PUT";
httpRequest1.ContentLength = Arrbyte.Length;
if (rangeStartOffset == 0)
{
EndOffset = Arrbyte.Length - 1;
}
else
{
EndOffset = rangeStartOffset + Arrbyte.Length - 1;
if (EndOffset > p_lenth)
{
EndOffset = Convert.ToInt32(p_lenth);
httpRequest1.ContentLength = EndOffset - rangeStartOffset;
}
}//5120000;5242880
httpRequest1.Headers["Content-Range"] = "bytes " + rangeStartOffset + "-" + EndOffset + "/" + p_lenth; //"bytes */" + p_lenth; //
httpRequest1.ContentType = "message/rfc822";
httpRequest1.Timeout = 6000000;
UTF8Encoding encoding = new UTF8Encoding();
Stream stream = httpRequest1.GetRequestStream();
stream.Write(Arrbyte, 0, Arrbyte.Length);
stream.Close();
try
{
using (Stream f_ObjHttpStream = httpRequest1.GetRequestStream())
{
}
}
catch (Exception EX)
{
}
WebResponse response1 = null;
try
{
using (response1 = (HttpWebResponse)httpRequest1.GetResponse())
{
}
}
catch (Exception ex)
{
// UploadUrl = response1.Headers["Location"].ToString();
}
//4194303
rangeStartOffset = EndOffset +1;
}
catch (Exception)
{
}
}

how to use Management API in Windows Form / C# - but The remote server returned an error: (400) Bad Request

I have a problem in API Management, I want to create images in item 1 item, but I still can not do it forever. I use c # language, I feel depressed
i want to create a resource in catchoom.
can you help me
byte[] buffer = null;
byte[] data = null;
byte[] data1 = null;
HttpWebRequest request = null;
int bytesRead = 0;
long length = 0;
string boundary = DateTime.Now.Ticks.ToString("x");
// string boundary = "AaB03x";
StringBuilder sb = null;
// Create the HttpWebRequest object
request = (HttpWebRequest)HttpWebRequest.Create("https://crs.catchoom.com/api/v0/image/?api_key=5aba12ba6974c04ebc95da45ba1597d27d75238f");
// Specify the ContentType
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
// Specify the Method
request.Method = "POST";
request.KeepAlive = false;
// Create the StringBuilder object
sb = new StringBuilder();
// Constrcut the POST header message
sb.AppendLine("");
sb.AppendLine("--" + boundary);
sb.AppendLine("Content-Disposition: form-data; name=\"anh\"");
sb.AppendLine("");
sb.AppendLine("/api/v0/item/aee726ff67274fcb80f4c24f27861c1e/");
sb.AppendLine("--" + boundary);
sb.AppendLine("Content-Disposition: file; name=\"anh\"; filename=\"anh\"");
sb.AppendLine("Content-Type: image/jpg");
sb.AppendLine("");
StringBuilder sb1 = new StringBuilder();
sb1.AppendLine("");
sb1.AppendLine("--" + boundary + "--");
// Convert the StringBuilder into a string
data = Encoding.UTF8.GetBytes(sb.ToString());
data1 = Encoding.UTF8.GetBytes(sb1.ToString());
//
using (FileStream fs = new FileStream(#"D:\17. NHATLINH\ToolKit_Catchoom\ToolKit_Catchoom\bin\Debug\aa.jpg", FileMode.Open, FileAccess.Read))
{
length = data.Length + fs.Length + data1.Length;
// đưa thông tin chiều dài của gói gửi đi vào
request.ContentLength = length;
//
using (Stream stream = request.GetRequestStream())
{
// ghi header vào gói gửi đi
stream.Write(data, 0, data.Length);
//
buffer = new Byte[checked((uint)Math.Min(4096, (int)fs.Length))];
// buffer = new Byte[fs.Length];
// Write the file contents
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
{
stream.Write(buffer, 0, bytesRead);
}
stream.Write(data1, 0, data1.Length);
//
try
{
Console.WriteLine(request.ContentType);
Console.WriteLine(sb.ToString() + sb1.ToString());
WebResponse responce = request.GetResponse();
Stream s = responce.GetResponseStream();
StreamReader sr = new StreamReader(s);
MessageBox.Show(sr.ReadToEnd());
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
}
}
Building a multipart-encoded request is an error-prone task ( it is normal if you feel frustrated trying ), I recommend you to use a library to handle this kind of things, no point in reinventing the wheel :)
If you are using the Microsoft .NET Framework >= 4.5, you may use the HttpClient class as this answer explains.
Hope this help you ;)

How to upload image signature in docusign by c#?

I want to upload an image to docusign by c#, but it does not work. Below is my code that I wrote with mvc4.
Please help me,
Thanks!
public class UploadFileController : Controller
{
static string email = "***"; // your account email
static string password = "***"; // your account password
static string integratorKey = "***"; // your account Integrator Key (found on Preferences -> API page)
static string baseURL = ""; // - we will retrieve this
static string accountId = "***"; // - we will retrieve this
static string userId = "***";
static string signatureName = "signature";
#region FormUpload
public static class FormUpload
{
private static readonly Encoding encoding = Encoding.UTF8;
public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, object> postParameters)
{
string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
string contentType = "multipart/form-data; boundary=" + formDataBoundary;
byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);
return PostForm(postUrl, userAgent, contentType, formData);
}
private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData)
{
HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
if (request == null)
{
throw new NullReferenceException("request is not a http request");
}
// Set up the request properties.
request.Method = "PUT";
request.ContentType = contentType;
// request.UserAgent = userAgent;
request.CookieContainer = new CookieContainer();
request.ContentLength = formData.Length;
string authenticateStr =
"<DocuSignCredentials>" +
"<Username>" + email + "</Username>" +
"<Password>" + password + "</Password>" +
"<IntegratorKey>" + integratorKey + "</IntegratorKey>" + // global (not passed)
"</DocuSignCredentials>";
request.Headers.Add("X-DocuSign-Authentication", authenticateStr);
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(formData, 0, formData.Length);
requestStream.Close();
}
return request.GetResponse() as HttpWebResponse;
}
private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
Stream formDataStream = new System.IO.MemoryStream();
bool needsCLRF = false;
foreach (var param in postParameters)
{
// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));
needsCLRF = true;
if (param.Value is FileParameter)
{
FileParameter fileToUpload = (FileParameter)param.Value;
// Add just the first part of this param, since we will write the file data directly to the Stream
StringBuilder headerbuilder = new StringBuilder();
String header1, header2, header3, header4, header5, header6, header7, header8, header9, header10, header11, header12, header13;
header1 = String.Format("--{0}\r\nContent-Disposition: form-data; name =\"HTTPMethod\"", boundary);
header2 = String.Format("\n--{0}\r\nContent-Disposition: form-data; name =\"MethodName\"", boundary);
header3 = String.Format("\n--{0}\r\nContent-Disposition: form-data; name =\"MethodURI\"", boundary);
header4 = String.Format("\n--{0}\r\nContent-Disposition: form-data; name =\"BaseURL\"", boundary);
header5 = String.Format("\n--{0}\r\nContent-Disposition: form-data; name =\"PublicPath\"", boundary);
header6 = String.Format("\n--{0}\r\nContent-Disposition: form-data; name =\"Protocol\"", boundary);
header7 = String.Format("\n--{0}\r\nContent-Disposition: form-data; name =\"Version\"", boundary);
header8 = String.Format("\n--{0}\r\nContent-Disposition: form-data; name =\"Username\"", boundary);
header9 = String.Format("\n--{0}\r\nContent-Disposition: form-data; name =\"Password\"", boundary);
header10 = String.Format("\n--{0}\r\nContent-Disposition: form-data; name =\"IntegratorKey\"", boundary);
header11 = String.Format("\n--{0}\r\nContent-Disposition: form-data; name =\"pram[accountId]\"", boundary);
header12 = String.Format("\n--{0}\r\nContent-Disposition: form-data; name =\"param[userId]\"", boundary);
header13 = String.Format("\n--{0}\r\nContent-Disposition: form-data; name =\"signatureName\"", boundary);
//headerbuilder.Append(
string header = string.Format("\n--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
boundary,
param.Key,
fileToUpload.FileName ?? param.Key,
fileToUpload.ContentType ?? "application/octet-stream");
headerbuilder.Append(header1);
headerbuilder.Append(header2);
headerbuilder.Append(header3);
headerbuilder.Append(header4);
headerbuilder.Append(header5);
headerbuilder.Append(header6);
headerbuilder.Append(header7);
headerbuilder.Append(header8);
headerbuilder.Append(header9);
headerbuilder.Append(header10);
headerbuilder.Append(header11);
headerbuilder.Append(header12);
headerbuilder.Append(header13);
headerbuilder.Append(header);
String a = headerbuilder.ToString();
formDataStream.Write(encoding.GetBytes(headerbuilder.ToString()), 0, encoding.GetByteCount(headerbuilder.ToString()));
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);
}
else
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
param.Value);
formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
string footer = "\r\n--" + boundary + "--\r\n";
formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));
// Dump the Stream into a byte[]
formDataStream.Position = 0;
byte[] formData = new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Close();
return formData;
}
public class FileParameter
{
public byte[] File { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }
public FileParameter(byte[] file) : this(file, null) { }
public FileParameter(byte[] file, string filename) : this(file, filename, null) { }
public FileParameter(byte[] file, string filename, string contenttype)
{
File = file;
FileName = filename;
ContentType = contenttype;
}
}
}
#endregion
public ActionResult Index()
{
// Read file data
FileStream fs = new FileStream("D:\\signature3.jpg", FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
fs.Close();
// Generate post objects
Dictionary<string, object> postParameters = new Dictionary<string, object>();
postParameters.Add("filename", "signature3.jpg");
postParameters.Add("fileformat", "jpg");
postParameters.Add("file", new FormUpload.FileParameter(data, "signature3.jpg", "image/jpg"));
// Create request and receive response
string postURL = "https://demo.docusign.net/restapi/v2/accounts/"+accountId+"/users/"+userId+"/signatures/"+signatureName+"/signature_image";
string userAgent = "Someone";
HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, userAgent, postParameters);
// Process response
StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
string fullResponse = responseReader.ReadToEnd();
webResponse.Close();
Response.Write(fullResponse);
return View();
}
}
DocuSign imposes a 200K limit on signature image files. See the DocuSign REST API guide for more info. Page 247 describes the set signature image call:
http://docusign.com/sites/default/files/REST_API_Guide_v2.pdf

POI not sending xls file as attachment , sending as string

one of my junior code is not sending excel file as attachment . It is sending file like
------=_Part_0_2066339629.1374147892060
Content-Type: text/plain; name="Service_Change_Alert_Thu Jul 18 17:14:50 IST 2013.xlsx"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="Service_Change_Alert_Thu Jul 18 17:14:50 IST 2013.xlsx"
UEsDBBQACAAIANqJ8kIAAAAAAAAAAAAAAAARAAAAZG9jUHJvcHMvY29yZS54bWytkV1LwzAUhu/7
K0Lu2yTr1BHaDlEGguLADsW7kB7bYvNBEu3892bdrCheennyPu/D4aRY79WA3sH53ugSs4xiBFqa
ptdtiXf1Jl3hdZUkhTQOts5YcKEHj2JL+xJ3IVhOiJcdKOGzGOuYvBinRIija4kV8lW0QBaUnhMF
QTQiCHKwpXbW4aOPS/vvykbOSvvmhknQSAIDKNDBE5Yx8s0GcMr/WZiSmdz7fqbGcczGfOLiRow8
3d0+TMunvfZBaAm4ShAqTnYuHYgADYoOHj4slPgrecyvrusNrhaU5Sm9SNmqZowvl/yMPhfkV//k
function is following
public void sendSeviceabilityMail(List<OctpinSaveBean> datalist)
throws MessagingException {
Session session = null;
Map<String, String> utilsMap = ApplicationBean.utilsProperties;
if (utilsMap == null || utilsMap.size() == 0)
utilsMap = ApplicationBean.getUtilsPropertyFileValues();
smtpHost = utilsMap.get("SMTPHost");
to = utilsMap.get("To");
try {
if (smtpHost != null && to != null) {
Date date = new Date();
XSSFWorkbook updateDataBook =
updatedServiceabilityExcel(datalist);
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHost);
props.put("To", to);
session = Session.getInstance(props, null);
String str = "strstr";
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setContent(str, "text/html");
BodyPart messageBodyPart = new MimeBodyPart();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
updateDataBook.write(baos);
byte[] bytes = baos.toByteArray();
DataSource ds = new ByteArrayDataSource(bytes,
"application/vnd.ms-excel");
DataHandler dh = new DataHandler(ds);
messageBodyPart.setDataHandler(dh);
String fileName = "Service_Change_Alert_" + date+".xlsx";
messageBodyPart.setFileName(fileName);
messageBodyPart.setHeader("Content-disposition", "attachment;
filename=\"" + fileName + "\"");
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart);
if (to != null && to.length() > 0) {
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("tech_noida
<tech_noida#xyz.com>"));
String[] toArray = to.split(",");
InternetAddress[] address = new
InternetAddress[toArray.length];
for (int i = 0; i < toArray.length; i++) {
address[i] = new InternetAddress(toArray[i]);
}
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Updated Serviceability Alert!!!");
msg.setContent(multipart);
msg.setSentDate(date);
try {
Transport.send(msg);
logger.info("Mail has been sent about the updated serviceability alert to :" + to);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is not related to POI, but with JavaMail (plus the way different email clients handles the specs and malformed emails). Try this:
Multipart multipart = new MimeMultipart();
MimeBodyPart html = new MimeBodyPart();
// Use actual html not "strstr"
html.setContent("<html><body><h1>Hi</h1></body></html>", "text/html");
multipart.addBodyPart(html);
// ...
// Joop Eggen suggestion to avoid spaces in the file name
String fileName = "Service_Change_Alert_"
+ new SimpleDateFormat("yyyy-MM-dd_HH:mm").format(date) + ".xlsx";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
updateDataBook.write(baos);
byte[] poiBytes = baos.toByteArray();
// Can be followed by the DataSource / DataHandler stuff if you really need it
MimeBodyPart attachment = new MimeBodyPart();
attachment.setFileName(filename);
attachment.setContent(poiBytes, "application/vnd.ms-excel");
//attachment.setDataHandler(dh);
attachment.setDisposition(MimeBodyPart.ATTACHMENT);
multipart.addBodyPart(attachment);
Update:
Also don't forget to call saveChanges to update the headers before sending the message.
msg.saveChanges();
See this answer for further details.

How to upload image to server in j2me from mobile by multipart/form-data?

While I am uploading the mobile and application number in multipart from-data from mobile it is hitting the server and data is storing in database.Now I added captured image to it and sent to server it is showing an exception.
org.apache.commons.fileupload.FileUploadBase$UnknownSizeException: the request was rejected because its size is unknown
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:305)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest (ServletFileUpload.java:116)
at org.apache.jsp.photo_jsp._jspService(photo_jsp.java:103)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:384)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:228)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:216)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process (Http11Protocol.java:634)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:445)
at java.lang.Thread.run(Unknown Source)
Here I am sending Mobile and application Number and captured image in bytes (imagecapturephoto1). Captured image is storing in view after taking photo.But when we are uploading it is showing exception.
try
{
System.out.println("url:" + serverUrl);
connection = (HttpConnection)Connector.open(serverUrl,Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=*****");
connection.setRequestProperty("User-Agent", "Profile/MIDP-2.1 Configuration/CLDC-1.1");
connection.setRequestProperty("Accept", "application/octet-stream" );
writer = new DataOutputStream(connection.openDataOutputStream());
// writer =new DataOutputStream( conn.openOutputStream());
String name="applicationNumber", name1="mobileNumber",name3="photo",
mimeType="text/plain",mimeType2="image/jpeg";
String value="123456789", value1="9849765432",fileName="applicationphoto.jpeg";
// write boundary
writeString(PREFIX);
writeString(boundary);
writeString(NEWLINE);
// write content header
writeString("Content-Disposition: form-data; name=\"" + name + "\"");
writeString(NEWLINE);
if (mimeType != null)
{
writeString("Content-Type: " + mimeType);
writeString(NEWLINE);
}
writeString("Content-Length: " + applicationNumber.length());
writeString(NEWLINE);
writeString(NEWLINE);
// write content
writeString(applicationNumber);
writeString(NEWLINE);
// write boundary
writeString(PREFIX);
writeString(boundary);
writeString(NEWLINE);
// write content header
writeString("Content-Disposition: form-data; name=\"" + name1 + "\"");
writeString(NEWLINE);
if (mimeType != null)
{
writeString("Content-Type: " + mimeType);
writeString(NEWLINE);
}
writeString("Content-Length: " + mobileNumber.length());
writeString(NEWLINE);
writeString(NEWLINE);
// write content
writeString(mobileNumber);
writeString(NEWLINE);
//uploading image...........
// write boundary
writeString(PREFIX);
writeString(boundary);
writeString(NEWLINE);
// write content header
writeString("Content-Disposition: form-data; name=\"" + name3
+ "\"; filename=\"" + fileName + "\"");
writeString(NEWLINE);
if (mimeType2 != null)
{
writeString("Content-Type: " + mimeType2);
writeString(NEWLINE);
}
writeString("Content-Length: " + imagecapturephoto1.length);
writeString(NEWLINE);
writeString(NEWLINE);
// write content
// SEND THE IMAGE
int index = 0;
int size = 1024;
do
{
System.out.println("write:" + index);
if((index+size)<=imagecapturephoto1.length)
{
writer.write(imagecapturephoto1, index, size);
}
index+=size;
}while(index<imagecapturephoto1.length);
writeString(NEWLINE);
writeString(PREFIX);
writeString(boundary);
writeString(PREFIX);
writeString(NEWLINE);
writer.flush();
//writer.write("-- ***** -- \r\n".getBytes());
serverResponseMessage = connection.getResponseMessage();
InputStream inputstream = connection.openInputStream();
// retrieve the response from server
int chnumber;
StringBuffer sbuffer =new StringBuffer();
while( ( chnumber= inputstream.read() ) != -1 )
{
sbuffer.append( (char)chnumber );
}
String resonsestring=sbuffer.toString();
int end=resonsestring.length();
int tempstr=resonsestring.indexOf(">");
statusResponse=resonsestring.substring(tempstr+1, end);
statusResponse="SUCCESS";
//outputStream.close();
writer.close();
connection.close();
return serverResponseMessage;
}
catch (Exception ex)
{
//statusResponse="SUCCESS";
ex.printStackTrace();
return null;
}
Please suggest me,How we have to upload image from mobile.I was struck from last 10 days.please suggest me how to solve this issue.
Thanks in advance.
-Teja.
kindly try following code segment, Please ignore lat-lon coding.
private void postImageToServer(String curURL) throws Exception
{
// Open up a http connection with the Web server for both send and receive operations
midlet.get_frmLog().append("HttpConnection Enter");
httpConnection = (HttpConnection)Connector.open(URL, Connector.READ_WRITE);
// Set the request method to POST
httpConnection.setRequestMethod(HttpConnection.POST);
// Set the request headers
httpConnection.setRequestProperty(ConstantCodes.ACTION_MODE_PARAMETER,action);
httpConnection.setRequestProperty(ConstantCodes.USER_NAME_REQUEST_PARAMETER,userName);
//httpConnection.setRequestProperty("lat","22.955804");
//httpConnection.setRequestProperty("lon","72.685876");
//httpConnection.setRequestProperty("lat",LatLonFetcherThread.getLatitude());
//httpConnection.setRequestProperty("lon",LatLonFetcherThread.getLongitude());
/*lat = "23.0172";
lon = "72.3416";*/
if ( midlet.get_choiceGroupGPS().getSelectedIndex() == 0 )
{
lat = LatLonFetcherThread.getLatitude();
lon = LatLonFetcherThread.getLongitude();
}
else if ( midlet.get_choiceGroupGPS().getSelectedIndex() != 0 ) // Added By KALPEN
{
if ( midlet.state == mREPORTER.STATE_READING )
{
double xLat,xLon;
try
{
GpsBt.instance().start();
//while (true)
{
gpsBt = GpsBt.instance();
if ( gpsBt.isConnected() )
{
location = gpsBt.getLocation();
//lat = location.utc;
//lon = location.utc;
lat = (location.latitude + location.northHemi);
lon = (location.longitude + location.eastHemi);
lat = lat.substring(0,lat.length()-1);
lon = lon.substring(0,lon.length()-1);
xLat = Double.parseDouble(lat) / (double)100.00;
xLon = Double.parseDouble(lon) / (double)100.00;
lat = xLat + "";
lon = xLon + "";
lat = lat.substring(0,7);
lon = lon.substring(0,7);
//lat = "23.0172";
//lon = "72.3416";
}
Thread.sleep(100);
}
}
catch ( Exception e ) { lat = "23.0172"; lon = "72.3416"; }
}
}
httpConnection.setRequestProperty("lat",lat); // Modifed by KALPEN
httpConnection.setRequestProperty("lon",lon); // Modifed by KALPEN
//String latlongStr = "Latitude: " + LatLonFetcherThread.getLatitude()
// + "\nLongitude: " + LatLonFetcherThread.getLongitude();
/*String latlongStr = "lat: 22.955804" + "lon: 72.685876";*/
//#style screenAlert
/*Alert latlonAlert = new Alert("LatLon alert" );
latlonAlert.setString(latlongStr);
mREPORTER.display.setCurrent(latlonAlert);*/
if(eventName == null || eventName.equals(""))
eventName = "default";
// all the headers are sending now and connection channel is establising
httpConnection.setRequestProperty(ConstantCodes.EVENT_NAME_REQUEST_PARAMETER, eventName);
httpConnection.setRequestProperty(ConstantCodes.CAMERAID_REQUEST_PARAMETER, cameraID);
httpConnection.setRequestProperty(ConstantCodes.COMPRESSION_MODE_REQUEST_PARAMETER, compressionMode);
midlet.get_frmLog().append("Write on server-->"+imageBytes.length);
DataOutputStream dos = httpConnection.openDataOutputStream();
dos.write(imageBytes);
midlet.threadFlag=true;
}
Above Method works fine with my code, as I am also trying to upload Image to Server.

Resources