Is it possible to store images to mongo GridFS directly form URL, which I get from API? or I have to store it locally and then insert it into mongo?
I tried to insert directly from URL, but C# driver gave me an error that URI is not supported..
The MongoGridFS class implements .NET's stream API so you should be able to use a MemoryStream to save the web response and insert into GridFS.
try
{
var server = MongoServer.Create("mongodb://192.168.1.8:27017/imgdb?safe=true");
var db = server.GetDatabase("imgdb");
string fileName = "logo-mongodb.png";
// Get image from URL or API
WebRequest req = WebRequest.Create("http://media.mongodb.org/" + fileName);
WebResponse response = req.GetResponse();
Console.WriteLine("Response length is " + response.ContentLength + " bytes");
// Copy from WebResponse to MemoryStream
MemoryStream memStream;
using (Stream responseStream = response.GetResponseStream())
{
memStream = new MemoryStream();
byte[] buffer = new byte[1024];
int byteCount;
do
{
byteCount = responseStream.Read(buffer, 0, buffer.Length);
memStream.Write(buffer, 0, byteCount);
} while (byteCount > 0);
responseStream.Close();
}
// Reset to beginning of stream
memStream.Seek(0, SeekOrigin.Begin);
// Save to GridFS
var gridFsInfo = db.GridFS.Upload(memStream, fileName);
// Success!
Console.WriteLine("Success!");
}
catch (Exception err)
{
Console.WriteLine("Something went wrong: "+err.Message);
}
Related
String reqURL = baseUrl + data_oauth.get(PropLoad.getTestXmlData("URL"));
Template template = new Template();
String updatedUrl = template.getUpdatedURL(reqURL);
Map<String, String> headers = Template.getRequestData(data_oauth,PropLoad.getTestXmlData("HEADER"));
headers.entrySet().toString();
String updatedAuthor = template.getAuthorizationHeader(headers, methodDesc);
headers.put("Authorization", updatedAuthor);
String xmlRequest = Template.generateStringFromResource(data_oauth,"xmlbody");
Response response = webCredentials_rest.postCallWithHeaderAndBodyParamForXml(headers, xmlRequest, updatedUrl);
// am getting Unmarshalled as in response, can any help me on posting an POST request with XML body in it
You can send it like this:
URL url = new URL(urlString);
URLConnection connenction = url.openConnection();
OutputStream output = connenction.getOutputStream();
InputStream input = new FileInputStream(xmlFile);
byte[] buffer = new byte[4096];
int len;
while ((len = input .read(buffer)) >= 0) {
out.write(buffer, 0, len);
}
input .close();
output.close();
And read the response like this:
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connenction.getInputStream()));
String readLine = reader.readLine();
while (readLine != null) {
stringBuilder.append(readLine);
readLine = br.readLine();
}
I googled alot but not getting any documentation of Adobe AEM for restfull API. I tried the .Net code from
https://helpx.adobe.com/experience-manager/using/using-net-client-application.html.
But it creates folder instead of uploading content.
What are the parameters we need to pass to upload any image, mp4, pdf etc. Below is my c# code.
protected void Button1_Click(object sender, EventArgs e)
{
string fileName=FileUpload1.FileName;
String postURL = "http://localhost:4502/content/dam/geometrixx/" + fileName;
System.Uri uri = new System.Uri(postURL);
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(uri);
NetworkCredential nc = new NetworkCredential("admin", "admin");
httpWReq.Method = "POST";
httpWReq.Credentials = nc;
httpWReq.ContentType = "application/x-www-form-urlencoded";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = FileUpload1.FileBytes;
httpWReq.ContentLength = data.Length;
using (System.IO.Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string responseText = string.Empty;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
responseText = reader.ReadToEnd();
}
TextBox1.Text = responseText;
}
I'm not familar with .Net, but the question is more about how to create an asset in AEM. You didn't specify any version, so I tested my code only on AEM 5.6.1, but it should work also on AEM 6.X. In the following snippet you can see how you can upload new file using curl into a folder of your choice in dam, so you have only to make the call from your .Net code:
curl -u admin:admin -X POST -F file=#"/absolute/path/to/your/file.ext" http://localhost:4502/content/dam/the/path/you/wish/to/upload/myfolder.createasset.html
You are sending a POST request to the dam path where the file have to be uploaded with the selector "createasset" and the extension "html".
.net code for uploading files on Aem. Try below code.
var filelocation = AppDomain.CurrentDomain.BaseDirectory + "Images\\YourFile with Extension";
FileStream stream = File.OpenRead(filelocation);
byte[] fileBytes = new byte[stream.Length];
stream.Read(fileBytes, 0, fileBytes.Length);
stream.Close();
var httpClientHandler = new HttpClientHandler()
{
Credentials = new NetworkCredential("admin", "Your Password"),
};
//var httpClient = new HttpClient(httpClientHandler);
using (var httpClient = new HttpClient(httpClientHandler))
{
var requestContent = new MultipartFormDataContent();
var imageContent = new ByteArrayContent(fileBytes);
requestContent.Add(imageContent, "file", "file nmae with extension");
var response1 = httpClient.PostAsync("http://siteDomain/content/dam/yourfolder.createasset.html", requestContent);
var result = response1.Result.Content.ReadAsStringAsync();
}
Am using Voice RSS to do text to speech translation for my java application. I have used clients like RESTY in my past to handle simple json requests which am comfortable with. But in this case, the server (Voice RSS) is returning content type as audio, am unsure how to handle and unwrap this as a java client. Any help would be greatly appreciated
Thanks
Karthik
I figured out that you can use Url and BufferedInputStream to download the response from the web service as a byte array or as an OutputStream which you can save it as anything.
InputStream in = null;
ByteArrayOutputStream outputStream = null;
byte[] byteArray = null;
try {
URL link = new URL("YOUR_URL");
in = new BufferedInputStream(link.openStream());
outputStream = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1 != (n = in.read(buf))) {
outputStream.write(buf, 0, n);
}
byteArray = outputStream.toByteArray();
}catch (Exception ex){
throw ex;
}finally {
if(in != null) in.close();;
if(outputStream != null) outputStream.close();
}
I am using GWT.
I have to download a file file from server to client.
Document is in the external repository.
Client sends the id of the document through a Servlet.
On server side: Using this ID document is retrieved:
Document document = (Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
ByteArrayInputStream inputStream = (ByteArrayInputStream) contentStream.getStream();
int c;
while ((c = inputStream.read()) != -1) {
System.out.print((char) c);
}
String mime = contentStream.getMimeType();
String name = contentStream.getFileName();
InputStream strm = contentStream.getStream();
Here I can read the document.
I want to send this to the client.
How do I make this a file and send it back to the client?
In Your Servlet:
Document document =(Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
String name = contentStream.getFileName();
response.setHeader("Content-Type", "application/octet-stream;");
response.setHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
OutputStream os = response.getOutputStream();
InputStream is =
(ByteArrayInputStream) contentStream.getStream();
BufferedInputStream buf = new BufferedInputStream(is);
int readBytes=0;
while((readBytes=buf.read())!=-1) {
os.write(readBytes);
}
os.flush();
os.close();// *important*
return;
You can create a standard servlet (which extends HttpServlet and not RemoteServiceServlet) on server side and opportunity to submit the id as servlet parameter on client side.
Now you need after getting request create the excel file and send it to the client. Browser shows automatically popup with download dialog box.
But you should make sure that you set the right content-type response headers. This header will instruct the browser which type of file is it.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileId = reguest.getParameter("fileId"); // value of file id from request
File file = CreatorExel.getFile(fileId); // your method to create file from helper class
// setting response headers
response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", file.length());
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
input = new BufferedInputStream(fileInput);
output = new BufferedOutputStream(outputStream);
int count;
byte[] buffer = new byte[8192]; // buffer size is 512*16
while ((count = input.read(buffer)) > 0) {
output.write(buffer, 0, count);
}
} finally {
if (output != null) {
try {
output.close();
} catch (IOException ex) {
}
}
if (input != null) {
try {
input.close();
} catch (IOException ex) {
}
}
}
I am using WCF restful service to upload image to my databse
Code:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "AddDealImage/{id}")]
long AddDealImage(string id, Stream image);
public long AddDealImage(string id, Stream image)
{
//add convert Stram to byte[]
byte[] buffer = UploadFile.StreamToByte(image);
//create image record for database
Img img = ImgService.NewImage(DateTime.Now.ToFileTime().ToString(), "", buffer, "image/png");
ImgService.AddImage(img);
//return image id
return img.ImageId;
}
public static byte[] StreamToByte(Stream stream)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
Problem:
When i upload my photo via iPhone the POST was Successful. New image id is returned, and I can see the new record created in the database.
However when I try to convert binary from DB record to Image Stream: I got error:
"No imaging component suitable to complete this operation was found."
it seems that the MemoryStream is corrupted.
//photoBytes from database
MemoryStream photoStream = new MemoryStream(photoBytes)
//Error happened here
var photoDecoder = BitmapDecoder.Create(
photoStream,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.None);
Plus, the error only happens when image is uploaded via WCF Restful service.
It works perfectly if the image is uploaded via web form.
Question:
Where did i do wrong or missed?
how can i write a test client to test this upload api?
many thanks
the code above actually works.
the part I missed is the transferModel you need to set it to "Streamed" in web.config
Code for testing:
static void Main()
{
string filePath = #"C:\Users\Dizzy\Desktop\600.png";
string url = "http://localhost:13228/ApiRestful.svc/AddDealImage/96";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "text/xml";
request.Method = "POST";
using (Stream fileStream = File.OpenRead(filePath))
using (Stream requestStream = request.GetRequestStream())
{
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int byteCount = 0;
while ((byteCount = fileStream.Read(buffer, 0, bufferSize)) > 0)
{
requestStream.Write(buffer, 0, byteCount);
}
}
string result;
using (WebResponse response = request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
Console.WriteLine(result);
}