I have an ASP.NET MVC application that sends SMS from the web, problem is it doesn't send some special characters such as ~!##$&, when I send something like &&&&, it doesn't send SMS, if I send something like dan&dan it will send the first dan and remove remaining character and word.
Hare is my code:
public ActionResult SendSms(SendBatch member)
{
StreamReader objReader;
WebClient client = new WebClient();
string mess = member.Message;
string cell = member.Cell;
string pass = "mypassword";
string user = "username";
string baseurl = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0?" + "username=" + user + "&" + "password=" + pass + "&" + "message=" + mess + "&" + "msisdn=" + cell;
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(baseurl);
try
{
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
objReader = new StreamReader(objStream);
objReader.Close();
}
catch (Exception ex)
{
ex.ToString();
}
}
Hope someone can assist.
Because you use Get method to call SMS web service, illegal characters automatically removed from your SMS. You need to use HttpUtility.UrlEncode to encode characters before sending.
Thanks so much for the light, i manage to find a solution using HttpUtility.UrlEncode:
public ActionResult SendSms(SendBatch member)
{
StreamReader objReader;
WebClient client = new WebClient();
string mess = member.Message;
string cell = member.Cell;
string pass = "mypassword";
string user = "username";
string message = HttpUtility.UrlEncode(mess, System.Text.Encoding.GetEncoding("ISO-8859-1"));
string baseurl = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0?" + "username=" + user + "&" + "password=" + pass + "&" + "message=" + message + "&" + "msisdn=" + cell;
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(baseurl);
try
{
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
objReader = new StreamReader(objStream);
objReader.Close();
}
catch (Exception ex)
{
ex.ToString();
}
}
a third party service says my service is miss configures
how can I get the plain text of a request on a servlet? I need to show what my service is well configured
any idea?
[Edit] here code:
System.out.println(request.getMethod() + " " + request.getPathInfo() + "" + request.getProtocol());
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
System.out.println(headerName + ": " + request.getHeader(headerName));
}
Enumeration<String> params = request.getParameterNames();
while(params.hasMoreElements()){
String paramName = params.nextElement();
System.out.print(paramName+"="+request.getParameter(paramName));
if(params.hasMoreElements()){
System.out.print("&");
}
}
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString();
System.out.println(data);
To be sure, nothing beats a packet sniffer such as Wireshark. Take the time to install it and learn how to use it - it will save you a lot of time when doing web development.
I am using docusign rest api in my asp.net mvc application. I uploaded a .docx file to docusign. After signing, i am downloading this file . It gets downloaded as .docx file itself. But not able to open it. When I open the same file with adobe reader, it can be opened as pdf file. Can anyone help me to download the signed document as pdf so that i can open it easily?
static string email = "****"; // your account email
static string password = "****"; // your account password
static string integratorKey = "******";
static string recipientName = "***";
static string documentName = "test1.docx";
static string baseURL = "";
public void UploadtoDocuSign(int DocId, string DocName, int ObjectTypeId, int ObjectId)
{
try
{
User _dealuser = _imanageVacancy.GetDealById(ObjectId).LeadUser;
string recipientName = _dealuser.FirstName + " " + _dealuser.LastName; // provide a recipient (signer's) name
string documentName = DocName;
string recipientEmail = _dealuser.EmailAddress;
string sectionname = "";
DocumentManager _docmanager = GetDocumentById(DocId);
if (_docmanager.SectionID != null)
sectionname = "\\" + GetSectionName_additionalDoc((int)_docmanager.SectionID);
string FileNameWithPath = CommonFunctions.ConfigReader.GetConfigValue("appSettings", "FileUploadPath") + "\\Documents\\" + EnumsNeeded.VacancySubMenu.Deal.ToString() + "\\" + ObjectId + sectionname + "\\" + documentName;
//============================================================================
// STEP 1 - Login API Call (used to retrieve your baseUrl)
//============================================================================
// Endpoint for Login api call (in demo environment):
string url = "https://demo.docusign.net/restapi/v2/login_information";
// set request url, method, and headers. No body needed for login api call
HttpWebRequest request = initializeRequest(url, "GET", null, email, password);
// read the http response
string response = getResponseBody(request);
// parse baseUrl from response body
baseURL = parseDataFromResponse(response, "baseUrl");
//============================================================================
// STEP 2 - Send Signature Request from Template
//============================================================================
/*
This is the only DocuSign API call that requires a "multipart/form-data" content type. We will be
constructing a request body in the following format (each newline is a CRLF):
--AAA
Content-Type: application/xml
Content-Disposition: form-data
<XML BODY GOES HERE>
--AAA
Content-Type:application/pdf
Content-Disposition: file; filename="document.pdf"; documentid=1
<DOCUMENT BYTES GO HERE>
--AAA--
*/
// append "/envelopes" to baseURL and use for signature request api call
url = baseURL + "/envelopes";
// construct an outgoing XML formatted request body (JSON also accepted)
// .. following body adds one signer and places a signature tab 100 pixels to the right
// and 100 pixels down from the top left corner of the document you supply
string xmlBody =
"<envelopeDefinition xmlns=\"http://www.docusign.com/restapi\">" +
"<emailSubject>DocuSign API - Signature Request on Document</emailSubject>" +
"<status>sent</status>" + // "sent" to send immediately, "created" to save as draft in your account
// add document(s)
"<documents>" +
"<document>" +
"<documentId>1</documentId>" +
"<name>" + documentName + "</name>" +
"</document>" +
"</documents>" +
// add recipient(s)
"<recipients>" +
"<signers>" +
"<signer>" +
"<recipientId>1</recipientId>" +
"<email>" + recipientEmail + "</email>" +
"<name>" + recipientName + "</name>" +
"<tabs>" +
"<signHereTabs>" +
"<signHere>" +
"<xPosition>100</xPosition>" + // default unit is pixels
"<yPosition>100</yPosition>" + // default unit is pixels
"<documentId>1</documentId>" +
"<pageNumber>4</pageNumber>" +
"</signHere>" +
"</signHereTabs>" +
"</tabs>" +
"</signer>" +
"</signers>" +
"</recipients>" +
"</envelopeDefinition>";
// set request url, method, headers. Don't set the body yet, we'll set that separelty after
// we read the document bytes and configure the rest of the multipart/form-data request
request = initializeRequest(url, "POST", null, email, password);
// some extra config for this api call
configureMultiPartFormDataRequest(request, xmlBody, documentName, FileNameWithPath);
// read the http response
response = getResponseBody(request);
string envelopeId = parseDataFromResponse(response, "envelopeId");
_docmanager.DocuSignReferenceId = envelopeId;
_docmanager.DocuSignStatus = "Sent";
_iDocRep.Update(_docmanager);
_unitOfWork.Commit();
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
string text = new StreamReader(data).ReadToEnd();
}
}
}
}
public void DocuSignDownload()
{
try
{
//============================================================================
// STEP 1 - Login API Call (used to retrieve your baseUrl)
//============================================================================
// Endpoint for Login api call (in demo environment):
string url = "https://demo.docusign.net/restapi/v2/login_information";
// set request url, method, and headers. No body needed for login api call
HttpWebRequest request = initializeRequest(url, "GET", null, email, password);
// read the http response
string response = getResponseBody(request);
// parse baseUrl from response body
baseURL = parseDataFromResponse(response, "baseUrl");
//============================================================================
// STEP 2 - Get Statuses of a set of envelopes
//============================================================================
//*** This example gets statuses of all envelopes in your account going back 1 month...
int curr_month = System.DateTime.Now.Month;
int curr_day = System.DateTime.Now.Day;
int curr_year = System.DateTime.Now.Year;
if (curr_month != 1)
{
curr_month -= 1;
}
else
{ // special case for january
curr_month = 12;
curr_year -= 1;
}
// append "/envelopes?from_date=MONTH/DAY/YEAR" and use in get statuses api call
// we need to URL encode the slash (/) chars, whos URL encoding is: %2F
url = baseURL + "/envelopes?from_date=" + curr_month.ToString() + "%2F" + curr_day.ToString() + "%2F" + curr_year.ToString();
// set request url, method, and headers. No request body for this api call...
request = initializeRequest(url, "GET", null, email, password);
// read the http response
response = getResponseBody(request);
string ComplenvIds = CompletedenvelopeIds(response);
ComplenvIds = ComplenvIds.TrimEnd(',');
string[] envIds = ComplenvIds.Split(',');
foreach (var envid in envIds)
{
DocumentManager _doc = _iDocRep.Get(x => x.DocuSignReferenceId == envid);
if (_doc != null)
{
DownloadCompletedEnvelopes(envid, _doc);
_doc.DocuSignStatus = "Completed";
_iDocRep.Update(_doc);
_unitOfWork.Commit();
}
}
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
string text = new StreamReader(data).ReadToEnd();
}
}
}
}
public void DownloadCompletedEnvelopes(string envId, DocumentManager doc)
{
try
{
//============================================================================
// STEP 1 - Login API Call (used to retrieve your baseUrl)
//============================================================================
// Endpoint for Login api call (in demo environment):
string url = "https://demo.docusign.net/restapi/v2/login_information";
// set request url, method, and headers. No body needed for login api call
HttpWebRequest request = initializeRequest(url, "GET", null, email, password);
// read the http response
string response = getResponseBody(request);
// parse baseUrl from response body
baseURL = parseDataFromResponse(response, "baseUrl");
//============================================================================
// STEP 2 - Get Envelope Document(s) List and Info
//============================================================================
// append "/envelopes/{envelopeId}/documents" to to baseUrl and use for next endpoint
url = baseURL + "/envelopes/" + envId + "/documents";
//url = baseURL + "/envelopes/";
// set request url, method, body, and headers
request = initializeRequest(url, "GET", null, email, password);
// read the http response
response = getResponseBody(request);
// store each document name and uri locally, so that we can subsequently download each one
Dictionary<string, string> docsList = new Dictionary<string, string>();
string uri, name;
using (XmlReader reader = XmlReader.Create(new StringReader(response)))
{
while (reader.Read())
{
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "envelopeDocument"))
{
XmlReader reader2 = reader.ReadSubtree();
uri = ""; name = "";
while (reader2.Read())
{
if ((reader2.NodeType == XmlNodeType.Element) && (reader2.Name == "name"))
{
name = reader2.ReadString();
}
if ((reader2.NodeType == XmlNodeType.Element) && (reader2.Name == "uri"))
{
uri = reader2.ReadString();
}
}// end while
docsList.Add(name, uri);
}
}
}
//============================================================================
// STEP 3 - Download the Document(s)
//============================================================================
//string envelopeID = "Some EnvelopeID";
//EnvelopePDF envPDF = apiService.RequestPDF(envelopeID);
foreach (KeyValuePair<string, string> kvp in docsList)
{
// append document uri to baseUrl and use to download each document(s)
url = baseURL + kvp.Value;
// set request url, method, body, and headers
request = initializeRequest(url, "GET", null, email, password);
request.Accept = "application/pdf"; // documents are converted to PDF in the DocuSign cloud
// read the response and store into a local file:
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
string sectionname = "";
if (doc.SectionID != null)
sectionname = "\\" + GetSectionName_additionalDoc((int)doc.SectionID);
using (MemoryStream ms = new MemoryStream())
using (FileStream outfile = new FileStream(CommonFunctions.ConfigReader.GetConfigValue("appSettings", "FileUploadPath") + "\\Documents\\" + EnumsNeeded.VacancySubMenu.Deal.ToString() + "\\" + doc.ObjectID + sectionname + "\\" + kvp.Key, FileMode.Create))
{
webResponse.GetResponseStream().CopyTo(ms);
if (ms.Length > int.MaxValue)
{
throw new NotSupportedException("Cannot write a file larger than 2GB.");
}
outfile.Write(ms.GetBuffer(), 0, (int)ms.Length);
}
}
Console.WriteLine("\nDone downloading document(s), check local directory.");
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
string text = new StreamReader(data).ReadToEnd();
}
}
}
}
//***********************************************************************************************
// --- HELPER FUNCTIONS ---
//***********************************************************************************************
public static HttpWebRequest initializeRequest(string url, string method, string body, string email, string password)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
addRequestHeaders(request, email, password);
if (body != null)
addRequestBody(request, body);
return request;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void addRequestHeaders(HttpWebRequest request, string email, string password)
{
// authentication header can be in JSON or XML format. XML used for this walkthrough:
string authenticateStr =
"<DocuSignCredentials>" +
"<Username>" + email + "</Username>" +
"<Password>" + password + "</Password>" +
"<IntegratorKey>" + integratorKey + "</IntegratorKey>" + // global (not passed)
"</DocuSignCredentials>";
request.Headers.Add("X-DocuSign-Authentication", authenticateStr);
request.Accept = "application/xml";
request.ContentType = "application/xml";
}
public static void addRequestBody(HttpWebRequest request, string requestBody)
{
// create byte array out of request body and add to the request object
byte[] body = System.Text.Encoding.UTF8.GetBytes(requestBody);
Stream dataStream = request.GetRequestStream();
dataStream.Write(body, 0, requestBody.Length);
dataStream.Close();
}
public static void configureMultiPartFormDataRequest(HttpWebRequest request, string xmlBody, string docName, string FileNameWithPath)
{
// overwrite the default content-type header and set a boundary marker
request.ContentType = "multipart/form-data; boundary=BOUNDARY";
// start building the multipart request body
string requestBodyStart = "\r\n\r\n--BOUNDARY\r\n" +
"Content-Type: application/xml\r\n" +
"Content-Disposition: form-data\r\n" +
"\r\n" +
xmlBody + "\r\n\r\n--BOUNDARY\r\n" + // our xml formatted envelopeDefinition
"Content-Type: application/pdf\r\n" +
"Content-Disposition: file; filename=\"" + docName + "\"; documentId=1\r\n" +
"\r\n";
string requestBodyEnd = "\r\n--BOUNDARY--\r\n\r\n";
// read contents of provided document into the request stream
FileStream fileStream = System.IO.File.OpenRead(FileNameWithPath);
// write the body of the request
byte[] bodyStart = System.Text.Encoding.UTF8.GetBytes(requestBodyStart.ToString());
byte[] bodyEnd = System.Text.Encoding.UTF8.GetBytes(requestBodyEnd.ToString());
Stream dataStream = request.GetRequestStream();
dataStream.Write(bodyStart, 0, requestBodyStart.ToString().Length);
// Read the file contents and write them to the request stream. We read in blocks of 4096 bytes
byte[] buf = new byte[4096];
int len;
while ((len = fileStream.Read(buf, 0, 4096)) > 0)
{
dataStream.Write(buf, 0, len);
}
dataStream.Write(bodyEnd, 0, requestBodyEnd.ToString().Length);
dataStream.Close();
}
public static string getResponseBody(HttpWebRequest request)
{
// read the response stream into a local string
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string responseText = sr.ReadToEnd();
return responseText;
}
public static string parseDataFromResponse(string response, string searchToken)
{
// look for "searchToken" in the response body and parse its value
using (XmlReader reader = XmlReader.Create(new StringReader(response)))
{
while (reader.Read())
{
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == searchToken))
return reader.ReadString();
}
}
return null;
}
public static string CompletedenvelopeIds(string response)
{
string compenvIds = "";
string envId = "";
// look for "searchToken" in the response body and parse its value
using (XmlReader reader = XmlReader.Create(new StringReader(response)))
{
while (reader.Read())
{
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "envelopes"))
{
XmlReader reader2 = reader.ReadSubtree();
while (reader2.Read())
{
if ((reader2.NodeType == XmlNodeType.Element) && (reader2.Name == "envelope"))
{
XmlReader reader3 = reader2.ReadSubtree();
envId = "";
while (reader3.Read())
{
if ((reader3.NodeType == XmlNodeType.Element) && (reader3.Name == "envelopeId"))
{
envId = reader3.ReadString();
}
if ((reader3.NodeType == XmlNodeType.Element) && (reader3.Name == "status"))
{
if (reader3.ReadString() == "completed")
compenvIds = string.Concat(compenvIds, envId + ",");
}
if ((reader3.NodeType == XmlNodeType.Element) && (reader3.Name == "status"))
{
DateTime date = reader3.ReadContentAsDateTime();
}
}
}
}
}
}
}
return compenvIds;
}
public List<Lookup> LookupCache()
{
List<Lookup> _lookup = (List<Lookup>)HttpContext.Current.Cache["Lookup"];
if (HttpContext.Current.Cache["Lookup"] == null)
_lookup = _imanageUser.UpdateCache();
return _lookup;
}
string GetSectionName_additionalDoc(int SectionId)
{
List<Lookup> _lookup = LookupCache();
string _section = _lookup.Find(x => x.LookupType == (int)EnumsNeeded.EnumTypes.AdditionalDocumentTypes && x.LookupId == SectionId).LookupDesc;
return _section;
}
All files that come from DocuSign are going to be .PDF files.
Your documents will be saved as the name they were uploaded as (often contain the extension). So if you're writing the file with the name that it is stored in DocuSign by DocumentPDF->Name. I would do a .Replace and replace the extension with .pdf.
I am working with the paypal using express checkout to get a billing agreement id.
I was following this guide:
https://www.x.com/developers/paypal/documentation-tools/how-authorize-and-run-reference-transaction-express-checkout
In the first step when i do "SetExpressCheckout":
The following is the code
public string SetExpressCheckout(string Amount)
{
string returnURL = "http://localhost:50325/ReviewOrder.aspx" + "?amount=" + Amount + "&PAYMENTREQUEST_0_CURRENCYCODE=USD";
string cancelURL = returnURL.Replace("ReviewOrder", "ExpCheckOut");
string strCredentials = "USER=" + strUsername + "&PWD=" + strPassword + "&SIGNATURE=" + strSignature;
string strNVP = strCredentials;
strNVP += "&PAYMENTREQUEST_0_PAYMENTACTION=AUTHORIZATION&&PAYMENTREQUEST_0_AMT=25" + "&L_BILLINGTYPE0=MerchantInitiatedBilling" + "&RETURNURL=" + returnURL;
strNVP += "&CANCELURL=" + cancelURL;
strNVP += "&METHOD=SetExpressCheckout&VERSION=" + strAPIVersion + "&DESC=test EC payment" +"&NOSHIPPING=0" ;
//Create web request and web response objects, make sure you using the correct server (sandbox/live)
HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(strNVPSandboxServer);
//Set WebRequest Properties
wrWebRequest.Method = "POST";
// write the form values into the request message
StreamWriter requestWriter = new StreamWriter(wrWebRequest.GetRequestStream());
requestWriter.Write(strNVP);
requestWriter.Close();
// Get the response.
HttpWebResponse hwrWebResponse = (HttpWebResponse)wrWebRequest.GetResponse();
StreamReader responseReader = new StreamReader(wrWebRequest.GetResponse().GetResponseStream());
// and read the response
string responseData = responseReader.ReadToEnd();
responseReader.Close();
return responseData;
}
The response is:
TOKEN=EC-09082530FY878870B&
TIMESTAMP=2013-03-25T00:45:56Z&
CORRELATIONID=3d33037174d55&
ACK=SuccessWithWarning&
VERSION=86&
BUILD=5479129&
L_ERRORCODE0=11452&
L_SHORTMESSAGE0=Merchant not enabled for reference transactions&
L_LONGMESSAGE0=Merchant not enabled for reference transactions&
L_SEVERITYCODE0=Warning
How to to get a BillingAgreeentd in Step 3:
Code for step 3 is:
public string GetBillingAgreementID()
{
string returnURL = "http://localhost:50325/ReviewOrder.aspx" + "?amount=" + Amount + "¤cy=USD";
string cancelURL = returnURL.Replace("ReviewOrder", "ExpCheckOut");
string strCredentials = "USER=" + strUsername + "&PWD=" + strPassword + "&SIGNATURE=" + strSignature;
string strNVP = strCredentials;
strNVP += "&RETURNURL=" + returnURL;
strNVP += "&CANCELURL=" + cancelURL;
strNVP += "&METHOD=CreateBillingAgreement&VERSION=" + strAPIVersion + "&TOKEN=" + Session["Token"];
//Create web request and web response objects, make sure you using the correct server (sandbox/live)
HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(strNVPSandboxServer);
//Set WebRequest Properties
wrWebRequest.Method = "POST";
// write the form values into the request message
StreamWriter requestWriter = new StreamWriter(wrWebRequest.GetRequestStream());
requestWriter.Write(strNVP);
requestWriter.Close();
// Get the response.
HttpWebResponse hwrWebResponse = (HttpWebResponse)wrWebRequest.GetResponse();
StreamReader responseReader = new StreamReader(wrWebRequest.GetResponse().GetResponseStream());
// and read the response
string responseData = responseReader.ReadToEnd();
responseReader.Close();
return responseData;
}
Response is:
TIMESTAMP=2013-03-25T00:51:34Z&
CORRELATIONID=854e6beed1e82&
ACK=Failure&
VERSION=86&
BUILD=5479129&
L_ERRORCODE0=11455&
L_SHORTMESSAGE0=Buyer did not accept billing agreement&
L_LONGMESSAGE0=Buyer did not accept billing agreement&
L_SEVERITYCODE0=Error
How to get a BillingAgreemntId?
Is that because of "L_SHORTMESSAGE0=Merchant not enabled for reference transactions" this message from "SetExpressCheckout" am i not able to get BillingAgreementID?
Please help me on this. Thanks.
You would need to contact PayPal and request this to be enabled on the account, if this is for a live account. If you are needing it enabled on the sandbox, you would need to contact PayPal MTS and have this enabled on your sandbox account.
I need write the image data in a particular directory on the server side but I am getting a null for the raw byte[] image upload data that I am trying to send from an html form and jquery ajaxuploader plugin from here.
Following is the snippet from the controller I am using to handle raw bytes of image being uploaded:
#RequestMapping(value = "uploadImage", method = RequestMethod.POST)
public void uploadImage(byte[] uploadData, Writer writer, HttpServletRequest request) throws IOException, JSONException {
//uploadData is turning out to be null
//..
}
#InitBinder
protected void initBinder(ServletRequestDataBinder binder) {
binder.registerCustomEditor(byte[].class,
new ByteArrayMultipartFileEditor());
}
I have got the following configured in the spring configuration file for handling uploads:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
I am using Spring MVC 3. Could someone guide me on how to send raw bytes of upload data?
Thanks.
First, if you're form is uploading an image, make sure your content type is "multipart/form-data". You might want to change your RequestMapping as follows:
#RequestMapping(value = "uploadImage", method = RequestMethod.POST, headers={"content-type=multipart/form-data"})
Also, I'd suggest using CommonsMultipartFile to handle the upload. Change your function signature as follows, where "fieldName" is the name of the input field in your form:
public void uploadImage(byte[] uploadData, Writer writer, HttpServletRequest request, #RequestParam("fieldName") CommonsMultipartFile file)
Then you can get the raw bytes as follows:
file.getBytes()
Make sure you include the commons-fileupload dependency for CommonsMultipartFile.
I'm using spring3 + jquery ajaxform and this works like a charm. Hope this helps!
Following is the JavaScript and HTML code I used on the client side that got things working:
JavaScript:
function createUploader(){
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: 'uploadImage',
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
debug: true,
onSubmit: function(id, fileName){
console.log("id - " + id + ", fileName - " + fileName);
},
onComplete: function(id, fileName, responseJSON) {
console.log("responseJSON - " + responseJSON);
}
});
}
window.onload = createUploader;
HTML:
<div id="file-uploader" >
<noscript>
<p>Please enable JavaScript to upload your property location images</p>
</noscript>
</div>
Controller:
#Controller
public class FranchiseeLocationImageController {
private static final Log logger = LogFactory.getLog(FranchiseeLocationImageController.class);
#Autowired
private ServletContext servletContext;
#Autowired
private FranchiseeLocationImageService franchiseeLocationImageService;
#RequestMapping(value = "uploadImage", method = RequestMethod.POST)
public void uploadImage(byte[] qqfile, Writer writer, #RequestParam("qqfile") String img, HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException{
FranchiseeLocationImage image = null;
PrintWriter pr = null;
InputStream is = null;
File file = null;
FileOutputStream fos = null;
String filename = request.getHeader("X-File-Name");
String imageId = FilenameUtils.removeExtension(img);
String imageFormat = franchiseeLocationImageService.getImageFormat();
String outputDir = servletContext.getRealPath("") + File.separator + franchiseeLocationImageService.getImagesDirectory() + File.separator;
File baseDirectory = null;
File output = null;
String path = FilenameUtils.removeExtension(img) + "." + imageFormat;
File outputDirectory = null;
HttpSession session = request.getSession();
/*
HttpSession session = request.getSession(false);
if(session == null) {
session = request.getSession();
}
*/
List<String> franchiseeLocationImages = (List<String>) session.getAttribute("franchiseeLocationImages");
if(franchiseeLocationImages == null) {
franchiseeLocationImages = new ArrayList<String>();
}
logger.debug( "filename - " + filename + " | img - " + img + " | img name - " + FilenameUtils.removeExtension(img) + " | img format - " + FilenameUtils.getExtension(img) + " | uploadData - " + qqfile + " | imageFormat - " + imageFormat);
/**
* Reading the image being uploaded and writing it to images/franchiseeLocation folder ["qqfile" is used instead of "X-File-Name" as "X-File-Name" gives encoded HTML name with "%20" for " "]
*/
try {
pr = response.getWriter();
is = request.getInputStream();
/*
baseDirectory = new File(outputDir);
baseDirectory.mkdirs();
file = new File(outputDir, FilenameUtils.removeExtension(img) + "." + imageFormat);
fos = new FileOutputStream(file);
int copiedNum = IOUtils.copy(is, fos);
*/
outputDirectory = new File(outputDir);
outputDirectory.mkdirs();
output = new File(outputDirectory, path);
BufferedImage sourceImage = ImageIO.read(is);
boolean written = ImageIO.write(sourceImage, imageFormat, output);
franchiseeLocationImages.add(img);
session.setAttribute("franchiseeLocationImages", franchiseeLocationImages);
logger.debug("franchiseeLocationImages - " + franchiseeLocationImages);
logger.debug("outputDirectory - " + outputDirectory + " | output - " + output + " | sourceImage - " + sourceImage + " | is - " + is + " | file - " + file + " |fos - " + fos + " | copiedNum - " + "copiedNum" + " | baseDirectory - " + baseDirectory + " | sourceImage - " + sourceImage + " | written - " + written);
/*
image = franchiseeLocationImageService.processProductImage(qqfile, imageId);
JSONObject json = new JSONObject();
json.put("path", image.getPath());
json.put("id", image.getId());
writer.write(json.toString());
*/
pr.print("{success: true}");
} finally {
writer.close();
/*
try {
fos.close();
is.close();
} catch (IOException ignored) {
}
*/
pr.flush();
pr.close();
}
}
#InitBinder
protected void initBinder(ServletRequestDataBinder binder) {
binder.registerCustomEditor(byte[].class,
new ByteArrayMultipartFileEditor());
}
private static String html2text(String html) {
return Jsoup.parse(html).text();
}
}