Image not able to uploaded to Amazon S3 server - asp.net

I am using the below code to upload image file Amazon AWS S3 server..
using (var msImage = new MemoryStream(arrayImage))
using (var msImageL1 = new MemoryStream())
using (var bmImage = (Bitmap)Image.FromStream(msImage))
using (var bmPicture01 = new Bitmap(924, 693))
using (Graphics gPicture01 = Graphics.FromImage(bmPicture01))
{
using (IAmazonS3 s3client = new AmazonS3Client(accessKey, secretKey, RegionEndpoint.APSoutheast1))
{
PutObjectRequest putObjectRequest = new PutObjectRequest
{
BucketName = bucketName,
Key = "sample/5.jpg",
InputStream = msImage
};
s3client.PutObject(putObjectRequest);
}
gPicture01.InterpolationMode = InterpolationMode.HighQualityBicubic;
gPicture01.DrawImage(bmImage, 0, 0, 924, 693);
bmPicture01.Save(msImageL1, ImageFormat.Jpeg);
using (IAmazonS3 s3client = new AmazonS3Client(accessKey, secretKey, RegionEndpoint.APSoutheast1))
{
PutObjectRequest putObjectRequest = new PutObjectRequest
{
BucketName = bucketName,
Key = "sample/6.jpg",
InputStream = msImageL1
};
s3client.PutObject(putObjectRequest);
}
}
The first code, which is uploading "5.jpg" is working fine, and uploading successfully. But the other code is now working and giving exception that,
Message=The request was aborted: The request was canceled.
Message=Cannot close stream until all bytes are written.
I am using Amazon Web Services SDK for .NET version 2.0.2.3
Please suggest what might be going wrong here..

Since there hasn't been any other answer and my first response got deleted because it "does not really answer the question", I'm going to try and rephrase it.
You said:
Please suggest what might be going wrong here..
My suggestion is that there is nothing wrong with you code. Instead it's a possible bug with version 2.0.1 and later. See https://forums.aws.amazon.com/thread.jspa?threadID=139612&tstart=0 (requires log in). I've tried with version 2.0.2.3 and the bug is still there.
You can test this by using a previous version.

The issue here is that bmPicture01.Save(msImageL1, ImageFormat.Jpeg); saves the bitmap to a string but doesn't reset the position of the stream to 0. You will need to do that before passing the stream to PutObject.

Related

Setting a password for a zip file

I'm trying to set a password for a zip file using SharpZipLib library with .Net Core.
I have followed this example in order to set a password, however once the zip file has been created, the files are in there and the zip file is create, however there is no password.
// Create a password for the Zipfolder
// https://github.com/icsharpcode/SharpZipLib/wiki/Zip-Samples
using (ICSharpCode.SharpZipLib.Zip.ZipFile ZipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(Path.GetFileName(destinationPath)))
{
ZipFile.Password = "foo";
ZipFile.Add(destinationPath, "");
}
None of the above answers worked for me,With that being said I found this Fast Zip class within the SharpZipLib library that has worked for me.
// Create a password for the Zipfolder
// https://github.com/icsharpcode/SharpZipLib/wiki
ICSharpCode.SharpZipLib.Zip.FastZip zipFile = new ICSharpCode.SharpZipLib.Zip.FastZip();
zipFile.Password = "foo";
zipFile.CreateEmptyDirectories = true;
zipFile.CreateZip(destinationPath,tempPath, true, "");
The only thing I don't like about it however is that is doesn't implement IDisposable
I used the Example from the wiki and it worked without a Problem.
Code:
using (FileStream fsOut = File.Create(#"d:\temp\sharplib_pwtest.zip"))
using (ZipOutputStream zipStream = new ZipOutputStream(fsOut)) {
zipStream.SetLevel(3);
zipStream.Password = "Testpassword";
var folderName = #"D:\temp\sharpZipLibTest\";
int folderOffset = folderName.Length + (folderName.EndsWith("\\") ? 0 : 1);
CompressFolder(folderName, zipStream, folderOffset);
}
You just need to put BeginUpdate() and CommitUpdate() and that will reflect in your output.
using (ICSharpCode.SharpZipLib.Zip.ZipFile ZipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(Path.GetFileName(destinationPath)))
{
ZipFile.BeginUpdate();
ZipFile.Password = "foo";
ZipFile.Add(destinationPath, "");
ZipFile.CommitUpdate();
}
Thanks for y'all help. I took #traveler3668 answer and added a little bit more details. I used paths from my project as an example.
This worked for me:
using System.Web.Security; //to generate password
using ICSharpCode.SharpZipLib.Zip;
string password = Membership.GeneratePassword(32, 10);
var zip = new FastZip();
zip.Password = password;
zip.CreateZip(
"C:\\dev\\InterfaceStatus\\InterfaceStatus\\App_Data\\test-folder_31-10-2022_11-23-54.zip",
"C:\\dev\\InterfaceStatus\\InterfaceStatus\\App_Data\\test-folder_31-10-2022_11-23-54",
true,
""
);

Empty file received using HTTP Post method

I'm trying to download a file using HTTP, and here is the code.
With this, I have a directory made with a correct name, and a file within the directory made with a correct name, but there is NOTHING WRITTEN in the file.
PostMethod post = new PostMethod(serverUrl);
post.setRequestEntity(entity);
httpclient.executeMethod(post);
File contentDirectory = new File(fileFullPath);
if(contentDirectory.exists() == false){
contentDirectory.mkdir();
}
File localFile = new File(fileFullPath + File.separator + filename);
int readBuf = 0;
byte[] buf = new byte[Utils.getBufferSize()]; (BufferSize Checked)
InputStream is = null;
is = post.getResponseBodyAsStream();
FileOutputStream fos = new FileOutputStream(localFile);
while((readBuf = is.read(buf))!= -1){
fos.write(buf, 0, readBuf);
logger.info("readBuf : "+readBuf);
}
is.close();
fos.close();enter code here
if(localFile.exists()) Transfer_Success = true;
Being a noob I am, turns out all this time I was sending post method to a wrong servlet. A mistake only novices make.
So I have the bytes transferred correctly, but this time the image files can't be open due to wrong encoding type or something. I'm on to resolving this.

Windows Phone: Upload file to ASP Server?

I need to upload a file to my server. I have no prior knowledge to server side programming and need some advice I can understand. I have my file (JPEG Image) in a byte array in my Windows Phone app. I now need to upload it to my server. I currently have a sample that uses HttpWebRequest with post, but I do not know how to handle the data in that post from the asp page. If you could explain how to do this it would be great, but I am open to any alternatives, providing they can be used with Windows Server.
The code I am currently using: ('b' is the byte array for the file)
var uri = "http://www.masonbogert.info/mcode/default.aspx";
var request = HttpWebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "image/jpeg"; // Change to whatever you're uploading.
request.BeginGetRequestStream((result1) =>
{
using (Stream stream = request.EndGetRequestStream(result1))
{
stream.Write(b, 0, b.Length);
}
request.BeginGetResponse((result2) =>
{
var response = request.EndGetResponse(result2);
// Optionally handle the response.
var responseStream = response.GetResponseStream();
Dispatcher.BeginInvoke(new readstreamdelegate(readstream), responseStream);
}, null);
}, null);
Remember, when it comes to ASP and any other server side programming I have no prior knowledge, so please explain!
You can try to use the "WebClient" class for getting it. More information you can get there: "http://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.80).aspx".
Please see this page: http://nediml.wordpress.com/2012/05/10/uploading-files-to-remote-server-with-multiple-parameters/#more-234

How can I import external files into SDL Tridion 2011 using core service?

I want to push PDF, Word and Excel files into SDL Tridion 2011 by using core service.
I tried below code but get this error:
Invalid value for property 'BinaryContent'. Unable to open uploaded file:
using (ChannelFactory<ISessionAwareCoreService> factory =
new ChannelFactory<ISessionAwareCoreService>("wsHttp_2011"))
{
ISessionAwareCoreService client = factory.CreateChannel();
ComponentData multimediaComponent = (ComponentData)client.GetDefaultData(
ItemType.Component, "tcm:19-483-2");
multimediaComponent.Title = "MultimediaFile";
multimediaComponent.ComponentType = ComponentType.Multimedia;
multimediaComponent.Schema.IdRef = "tcm:19-2327-8";
using (StreamUploadClient streamClient = new StreamUploadClient())
{
FileStream objfilestream = new FileStream(#"\My Documents\My Poc\images.jpg",
FileMode.Open, FileAccess.Read);
string tempLocation = streamClient.UploadBinaryContent("images.jpg",
objfilestream);
}
BinaryContentData binaryContent = new BinaryContentData();
binaryContent.UploadFromFile = #"C:\Documents and Settings\My Poc\images.jpg";
binaryContent.Filename = "images.jpg";
binaryContent.MultimediaType = new LinkToMultimediaTypeData()
{
IdRef ="tcm:0-2-65544"
};
multimediaComponent.BinaryContent = binaryContent;
IdentifiableObjectData savedComponent = client.Save(multimediaComponent,
new ReadOptions());
client.CheckIn(savedComponent.Id, null);
Response.Write(savedComponent.Id);
}
Have a read of Ryan's excellent article here http://blog.building-blocks.com/uploading-images-using-the-core-service-in-sdl-tridion-2011
All binary files are handled the same way - so his technique for images will be equally as valid for documents, just make sure you use a Schema with the appropriate mime types.
The process for uploading binaries into Tridion using the Core Service is:
Upload the binary data to the Tridion server using a StreamUploadClient. This returns you the path of the file on the Tridion server.
Create a BinaryContentData that points to the file on the Tridion server (so with the path you got back from step 1)
Create a ComponentData that refers to the the BinaryContentData from step 2
Save the ComponentData
You are setting the local path for your file in step 2.
binaryContent.UploadFromFile = #"C:\Documents and Settings\My Poc\images.jpg";
But Tridion will never be able to find that file there. You instead should set the path that you got back from UploadBinaryContent:
string tempLocation;
using (StreamUploadClient streamClient = new StreamUploadClient())
{
FileStream objfilestream = new FileStream(#"\My Documents\My Poc\images.jpg",
FileMode.Open, FileAccess.Read);
tempLocation = streamClient.UploadBinaryContent("images.jpg", objfilestream);
}
BinaryContentData binaryContent = new BinaryContentData();
binaryContent.UploadFromFile = tempLocation;
Note that the Ryan's original code does exactly that.

how to download files to a default dir without poping an option window in Flex/Air?

I'm writing a app with Flex/air,and i need a function that downloading files to the default dir without a pop-up window.i tried to use ftp instead of http but found it's not supported by air.how can i solve this problem?
This should be possible in AIR. I don't know if there's a direct API approach, but you should be able to load the bytes into memory and then flush them into a file. In pseudo-pseudo-code using File and FileStream:
// get the bytes
var loader:URLLoader = new URLLoader();
loader.load("http://www.stackoverflow.com");
...
var bytes:ByteArray = loader.data;
// get the file in the correct location
var f:File = File.documentsDirectory.resolvePath("myfile.txt");
// write the file
var fs:FileStream = new FileStream(f, FileMode.WRITE);
fs.writeBytes(bytes);
fs.close();
There are a few examples out there to look at.
None of this is possible in Flash Player because of the security limits #viatropos suggests.
I don't think you can do that as it's a Security violation. The user must be prompted with a download window so they can choose the directory. I think the thinking goes "if you don't prompt the user, then a Flash/Flex app could download a bunch of junk to their computer without their permission", and that would make adobe look bad :/. I wish you could though.
You can, however, download it using a server side script without asking the user for permission. I do that with ruby to accomplish what you're describing.
Hope that helps,
Lance
You can but only air version because you have to use FileStream
var ff:File = File.desktopDirectory.resolvePath("sample.dwg");
var u:String = obj_l.d1.selectedItem.data + "" + obj_l.d2.selectedItem.label;
var ll3:URLLoader = new URLLoader ();
u = GETURL() + u;
rr.url = u;
//ff.download(rr);
ll3.dataFormat = URLLoaderDataFormat.BINARY;
ll3.load(rr);
ll3.addEventListener(Event.COMPLETE , function (e:Event):void {
var stream:FileStream = new FileStream ();
stream.open(ff,FileMode.WRITE);
stream.writeBytes(ll3.data);
});

Resources