I use HigLabo.Net.Dropbox to upload a file to Dropbox. I created a App named synch and I am trying to upload a file. Below is my code
byte[] bytes = System.IO.File.ReadAllBytes(args[1]);
UploadFile(bytes,"sundas.jpg","/Apps/synch/");
public static void UploadFile(byte[] content, string filename, string target)
{
string App_key = "xxxxxxxxxxxxxxx";
string App_secret = "yyyyyyyyyyyyyy";
HigLabo.Net.OAuthClient ocl = null;
HigLabo.Net.AuthorizeInfo ai = null;
ocl = HigLabo.Net.Dropbox.DropboxClient.CreateOAuthClient(App_key, App_secret);
ai = ocl.GetAuthorizeInfo();
string RequestToken= ai.RequestToken;
string RequestTokenSecret= ai.RequestTokenSecret;
string redirect_url = ai.AuthorizeUrl;
AccessTokenInfo t = ocl.GetAccessToken(RequestToken, RequestTokenSecret);
string Token= t.Token;
string TokenSecret= t.TokenSecret;
DropboxClient cl = new DropboxClient(App_key, App_secret, Token, TokenSecret);
HigLabo.Net.Dropbox.UploadFileCommand ul = new HigLabo.Net.Dropbox.UploadFileCommand();
ul.Root = RootFolder.Sandbox;
Console.WriteLine(ul.Root);
ul.FolderPath = target;
ul.FileName = filename;
ul.LoadFileData(content);
Metadata md = cl.UploadFile(ul);
Console.WriteLine("END");
}
The code executes fine but the file is not getting upload in Dropbox.
Am I missing something? Is the path to upload correct? How do I view the file in Dropbox whether it is uploaded or not?
Is there a setting which I am missing while creating the app? I am just looking at the home page and I am expecting the file at the root folder. Am I correct?
Or do I need to look into some other location?
Thanks #smarx and
#Greg.
The below is the code to accomplish the task. Thanks again for your support, I hope this will be helpful for some one.
string filePath="C:\\Tim\\sundar.jpg";
RestClient client = new RestClient("https://api-content.dropbox.com/1/");
IRestRequest request = new RestRequest("files_put/auto/{path}", Method.PUT);
FileInfo fileInfo = new FileInfo(filePath);
long fileLength = fileInfo.Length;
request.AddHeader("Authorization", "Bearer FTXXXXXXXXXXXXXXXXXXXisqFXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
request.AddHeader("Content-Length", fileLength.ToString());
request.AddUrlSegment("path", string.Format("Public/{0}", fileInfo.Name));
byte[] data = File.ReadAllBytes(filePath);
var body = new Parameter
{
Name = "file",
Value = data,
Type = ParameterType.RequestBody,
};
request.Parameters.Add(body);
IRestResponse response = client.Execute(request);
Related
I am using a server with nodejs and writing file with multer. While using with kotlin I can easily send file with the following code with retrofit:
val reqFile: RequestBody = file.asRequestBody("image/*".toMediaTypeOrNull())
val body = MultipartBody.Part.createFormData("upload", file.name, reqFile)
val name = "upload".toRequestBody("text/plain".toMediaTypeOrNull())
//val token = ...token
val message = messageToUpload
.toRequestBody("text/plain; charset=utf-8".toMediaTypeOrNull())
val req: Call<ResponseBody?>? =
apiService!!.postImage("Bearer $token", name, message, body)
Log.d("Tag", "uploading file...")
multer middleware usage code:
router.post(
"/upload",
isValidUser,
multer({
storage: storage,
}).single("upload"),
async function (req, res) { //...
}
// Include the node file module
var fs = require("fs");
storage = multer.diskStorage({
destination: "./uploads/",
filename: async function (req, file, cb) {
cb(null, file.originalname);
},
});
However I am unsuccessful on sending file with httpClient with C#. I do not have enough knowledge with this. So I need suggestion of its usage to make the file written in my server, just like it does with kotlin retrofit requests.Maybe I am sending the wrong name. But all time I get file is undefined, while I access const fileName = req.file.filename;
Here is the code with C#:
string fullFilePath = #"C:\image.jpg";
var fileName = Path.GetFileName(fullFilePath);
using var requestContent = new MultipartFormDataContent();
//add file part
using (FileStream fs = File.OpenRead(fullFilePath))
{
using (var streamContent = new StreamContent(fs))
{
var fileContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
fileContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"");
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
requestContent.Add(fileContent, "upload", fileName);
var response1 = client.PostAsync(new Uri("http://localhost:3000/api/upload"), requestContent).Result;
string result = response1.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
}
}
I am trying to upload a pdf for processing to google's Document AI service. Using google's using Google.Cloud.DocumentAI.V1 for "C#". Looked at the github and docs, not much info. PDF is on the local drive. I converted the pdf to a byte array then converted that to a Bystring. Then set the request mime to "application/pdf" but it return was an error of:
Status(StatusCode="InvalidArgument", Detail="Unsupported input file format.", DebugException="Grpc.Core.Internal.CoreErrorDetailException: {"created":"#1627582435.256000000","description":"Error received from peer ipv4:142.250.72.170:443","file":"......\src\core\lib\surface\call.cc","file_line":1067,"grpc_message":"Unsupported input file format.","grpc_status":3}")
Code:
try
{
//Generate a document
string pdfFilePath = "C:\\Users\\maponte\\Documents\\Projects\\SettonProjects\\OCRSTUFF\\DOC071621-0016.pdf";
var bytes = Encoding.UTF8.GetBytes(pdfFilePath);
ByteString content = ByteString.CopyFrom(bytes);
// Create client
DocumentProcessorServiceClient documentProcessorServiceClient = await DocumentProcessorServiceClient.CreateAsync();
// Initialize request argument(s)
ProcessRequest request = new ProcessRequest
{
ProcessorName = ProcessorName.FromProjectLocationProcessor("*****", "mycountry", "***"),
SkipHumanReview = false,
InlineDocument = new Document(),
RawDocument = new RawDocument(),
};
request.RawDocument.MimeType = "application/pdf";
request.RawDocument.Content = content;
// Make the request
ProcessResponse response = await documentProcessorServiceClient.ProcessDocumentAsync(request);
Document docResponse = response.Document;
Console.WriteLine(docResponse.Text);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
This is the problem (or at least one problem) - you aren't actually loading the file:
string pdfFilePath = "C:\\Users\\maponte\\Documents\\Projects\\SettonProjects\\OCRSTUFF\\DOC071621-0016.pdf";
var bytes = Encoding.UTF8.GetBytes(pdfFilePath);
ByteString content = ByteString.CopyFrom(bytes);
You instead want:
string pdfFilePath = "path-as-before";
var bytes = File.ReadAllBytes(pdfFilePath);
ByteString content = ByteString.CopyFrom(bytes);
I'd also note, however, that InlineDocument and RawDocument are alternatives to each other - specifying either of them removes the other. Your request creation would be better written as:
ProcessRequest request = new ProcessRequest
{
ProcessorName = ProcessorName.FromProjectLocationProcessor("*****", "mycountry", "***"),
SkipHumanReview = false,
RawDocument = new RawDocument
{
MimeType = "application/pdf",
Content = content
}
};
We have a requirement of sending the jpeg files of a given directory to a Xamarin App.
Following is the code in the Web API.
public HttpResponseMessage DownloadMutipleFiles()
{
name = "DirectoryName";
var content = new MultipartContent();
var ids = new List<int> { 1,2};
var objectContent = new ObjectContent<List<int>>(ids, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
content.Add(objectContent);
var file1Content = new StreamContent(new FileStream(#"D:\Photos\" + name+"\\"+ "BL1408037_20191031124058_0.jpg", FileMode.Open));
file1Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("image/jpeg");
content.Add(file1Content);
var file2Content = new StreamContent(new FileStream(#"D:\Photos\" + name + "\\" + "BL1408037_20191031124058_1.jpg", FileMode.Open));
file2Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("image/jpeg");
content.Add(file2Content);
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = content;
return response;
}
Can some one help out with how to read from Xamarin app? Thanks in advance
This is the function I was able to use to send an image as a multi part data file! I just took the byte array given to me by the Xamarin Essentials image picker and passed it into this function:
public async Task SubmitImage(byte[] image, string imageName)
{
using (var client = new HttpClient())
{
string url = $"..."; // URL goes here
var token = Preferences.Get("AccessToken", "");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
var stream = new MemoryStream(image);
var content = new StreamContent(stream);
//Without a name we can't actually put the file in IFormFile. We need the equivalent
//"name" value to be "file" (used if you upload via an <input> tag). We could call it
//anything but file is simple
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
FileName = imageName,
Name = "file"
};
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(content);
var result = await client.PostAsync(url, multipartContent);
}
}
You can test this using a console application as well and just send over a picture from your computer, instead of doing this through the app
I try upload file in amazon s3, but always return this message.
My code:
AmazonS3Config S3Config = new AmazonS3Config()
{
ServiceURL = "s3.amazonaws.com",
CommunicationProtocol = Protocol.HTTP,
RegionEndpoint = RegionEndpoint.SAEast1
};
using (AmazonS3Client client = new AmazonS3Client(KEY_S3, PASSWORD, S3Config))
{
string pathInS3 = folder + "/" + fileName;
PutObjectRequest request = new PutObjectRequest();
request.WithBucketName(BUCKET_NAME);
request.WithKey(pathInS3);
request.WithInputStream(memoryStreamFile);
request.CannedACL = S3CannedACL.PublicReadWrite;
client.PutObject(request);
}
I had use lock in request and client but do not resolve.
I think the problem is the memoryStreamFile, please do double check trying to read the content of your memorystreamFile.So another way to upload files to AmazonS3 with C# is the following:
AmazonS3Config cfg = new AmazonS3Config();
cfg.RegionEndpoint = Amazon.RegionEndpoint.EUCentral1;// region endpoint
string bucketName = "your bucket";
AmazonS3Client s3Client = new AmazonS3Client("your access key", "your secret key", cfg);
string dataString ="your data ";
MemoryStream data = new System.IO.MemoryStream(UTF8Encoding.ASCII.GetBytes(dataString));
TransferUtility t = new TransferUtility(s3Client);
t.Upload(data, bucketName, "testUploadFromTransferUtility.txt");
I am trying to upload some documents to Box and create and retrieve a shared link for each of them.
This is the code I am using for it, but I always retrieve 403:access_denied_insufficient_permissions.
Any idea of why this is happening?
Hope you can help me! Thanks.
// CREATE THE FILE
BoxFileRequest req = new BoxFileRequest
{
Name = zipFile.Name,
Parent = new BoxRequestEntity { Id = newFolder.Id}
};
BoxFile uploadedFile = client.FilesManager.UploadAsync(req, stream).Result;
//REQUEST SHARED LINK
BoxSharedLinkRequest sharedLinkReq = new BoxSharedLinkRequest()
{
Access = BoxSharedLinkAccessType.open,
Permissions = new BoxPermissionsRequest
{
Download = BoxPermissionType.Open,
Preview = BoxPermissionType.Open,
}
};
BoxFile fileLink = fileManager.CreateSharedLinkAsync(uploadedFile.Id, sharedLinkReq).Result;
you need to give the access token and url. I have use the Following code and in JSON Format you will get the Response. For more reference check the box API document
HttpWebRequest httpWReq = HttpWebRequest)WebRequest.Create("https://api.box.com/2.0/folders/" + FolderID);
ASCIIEncoding encoding = new ASCIIEncoding();
string putData = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] data = encoding.GetBytes(putData);
httpWReq.Method = "PUT";
httpWReq.Headers.Add("Authorization", "Bearer ");
httpWReq.ContentType = "application/json";
httpWReq.ContentLength = data.Length;
Use the httpwebrequest PUT method after this.
Mark it as Answer if its helpful.
It looks as if you are using the 3rd party BoxSync V2 API object. If you would like to just code to the API directly I had a similar issue that you are having. If you view this post you will see the answer. Here is the code I use and it works.
string uri = String.Format(UriFiles, fileId);
string response = string.Empty;
string body = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] postArray = Encoding.ASCII.GetBytes(body);
try
{
using (var client = new WebClient())
{
client.Headers.Add("Authorization: Bearer " + token);
client.Headers.Add("Content-Type", "application/json");
response = client.UploadString(uri, "PUT", body);
}
}
catch (Exception ex)
{
return null;
}
return response;