ASP.NET Web API 2 file upload - asp.net

I would like to know how best to handle file upload and addtional information added to the file to be uploaded using ASP.NET Web API 2 without MVC components. I have google the net and I can tell you I am more confused than I expected.
The Additional info will be stored in db and the file on the disk.
So far the Web API app I am building does not support multipart/form-data. It only supports the default media types. I know I need to create a media formatter.
Pls help.

I had wrote Javascript split File and upload to WEB API . i think you can reference my backend codes
In front-end you need using below code to upload your File
var xhr = new self.XMLHttpRequest();
xhr.open('POST', url, false);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.send(chunk);
In backend use Request.InputStream.Read to catch your file bytes
[HttpPost]
[ValidateInput(false)]
public string fileUpload(string filename)
{
byte[] file = new byte[Request.InputStream.Length];
Request.InputStream.Read(file, 0, Convert.ToInt32(Request.InputStream.Length));
BinaryWriter binWriter = new BinaryWriter(new MemoryStream());
binWriter.Write(file);
StreamReader reader = new StreamReader(binWriter.BaseStream);
reader.BaseStream.Position = 0;
//This example is recevied text file
while ((line = reader.ReadLine()) != null)
{
};
}

You can just serialize your file data into BASE64 and send them as a string in case of multipart/from-data is not allowed for some reason.

Related

What is the path of the Json file in Android at Xamarin.Forms?

I am developing an application for Android using Xamarin.
I have created a JsonData folder in the Android project and created a Setting.json file.
\MyApp\MyApp.Android\JsonData\Setting.json
In the properties, we set the Copy when new.
The following folders in the local environment contain the files.
\MyApp\MyApp.Android\bin\Debug\JsonData\Setting.json
I want to load this file in the actual Android device.
When I do this, it tells me that the file is missing.
Could not find a part of the path "/JsonData/Setting.json."
Try
{
var text = File.ReadAllText("JsonData/Setting.json", Encoding.UTF8);
var setting = JsonConvert.DeserializeObject<Setting>(text);
}
catch(Exception exception)
{
var error = exception.Message;
}
What is the path of the file in Android?
I think you're using File Handling in Xamarin.Forms incorrectly.
From the parameter of function File.ReadAllText, the app will access the file system to getSetting.json from folder JsonData in your android device.
The path of the file on each platform can be determined from a .NET Standard library by using a value of the Environment.SpecialFolder enumeration as the first argument to the Environment.GetFolderPath method. This can then be combined with a filename with the Path.Combine method:
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "temp.txt");
And you can read the file by code:
string text = File.ReadAllText(fileName);
In addition, from your code,I guess you want to Load your Embedded file( Setting.json) as Resources,right?
In this case,we should make sure the Build Action of your Setting.json is Embedded Resource.
And GetManifestResourceStream is used to access the embedded file using its Resource ID.
You can refer to the following code:
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(LoadResourceText)).Assembly;
Stream stream = assembly.GetManifestResourceStream("YourAppName.JsonData.Setting.json");
string text = "";
using (var reader = new System.IO.StreamReader (stream))
{
text = reader.ReadToEnd ();
}
For more , you can check document : File Handling in Xamarin.Forms.
And you can also check the sample code here: https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/workingwithfiles/ .

How to read a local json file and display

newbie here,I could not find any example on Xamarin Forms read a local json file and display it. I need to do a local testing to read the local Json file.
1) Where do I save the json file for reading? in Android and iOS Projects or just in PCL project?
2) How to read the file?
here the code but it is not complete as I dont how to read the file.
using (var reader = new System.IO.StreamReader(stream))
{
var json = reader.ReadToEnd();
var rootobject = JsonConvert.DeserializeObject<Rootobject>(json);
whateverArray = rootobject.Whatever;
}
The code miss the Path and others which required.
You can directly add your JSON file in PCL. Then change build action to Embedded Resource
Now you can read Json data by:
var assembly = typeof("<ContentPageName>").GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("Your_File.json");
using (var reader = new System.IO.StreamReader(stream))
{
var json = reader.ReadToEnd();
var data= JsonConvert.DeserializeObject<Model>(json);
}

Cannot upload large (>50MB) files to SharePoint 2010 document library

I'm trying to upload a large file to a document library, but it fails after just a few seconds. The upload single document fails silently, upload multiple just shows a failed message. I've turned up the file size limit on the web application to 500MB, and the IIS request length to the same (from this blog), and increased the IIS timeout for good measure. Are there any other size caps that I've missed?
Update I've tried a few files of various sizes, anything 50MB or over fails, so I assume something somewhere is still set to the webapp default.
Update 2 Just tried uploading using the following powershell:
$web = Get-SPWeb http://{site address}
$folder = $web.GetFolder("Site Documents")
$file = Get-Item "C:\mydoc.txt" // ~ 150MB
$folder.Files.Add("SiteDocuments/mydoc.txt", $file.OpenRead(), $false)
and get this exception:
Exception calling "Add" with "3" argument(s): "<nativehr>0x80070003</nativehr><nativestack></nativestack>There is no file with URL 'http://{site address}/SiteDocuments/mydoc.txt' in this Web."
which strikes me as odd as of course the file wouldn't exist until it's been uploaded? N.B. while the document library has the name Site Documents, it has the URL SiteDocuments. Not sure why...
Are you sure you updated the right webapp? Is the filetype blocked by the server? Is there adequate space in your content database? I would check ULS logs after that and see if there is another error since it seems you hit the 3 spots you would need too update.
for uploading a large file, you can use the PUT method instead of using the other ways to upload a document.
by using a put method you will save the file into content database directly. see the example below
Note: the disadvantage of the code below is you cannot catch the object that is responsible for uploading directly, on other word, you cannot update the additional custom properties of the uploaded document directly.
public static bool UploadFileToDocumentLibrary(string sourceFilePath, string targetDocumentLibraryPath)
{
//Flag to indicate whether file was uploaded successfuly or not
bool isUploaded = true;
try
{
// Create a PUT Web request to upload the file.
WebRequest request = WebRequest.Create(targetDocumentLibraryPath);
//Set credentials of the current security context
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = “PUT”;
// Create buffer to transfer file
byte[] fileBuffer = new byte[1024];
// Write the contents of the local file to the request stream.
using (Stream stream = request.GetRequestStream())
{
//Load the content from local file to stream
using (FileStream fsWorkbook = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read))
{
//Get the start point
int startBuffer = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length);
for (int i = startBuffer; i > 0; i = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length))
{
stream.Write(fileBuffer, 0, i);
}
}
}
// Perform the PUT request
WebResponse response = request.GetResponse();
//Close response
response.Close();
}
catch (Exception ex)
{
//Set the flag to indiacte failure in uploading
isUploaded = false;
}
//Return the final upload status
return isUploaded;
}
and here are an example of calling this method
UploadFileToDocumentLibrary(#”C:\test.txt”, #”http://home-vs/Shared Documents/textfile.pdf”);

Lose HttpServletRequest Parts After Reading Them

I have a servlet that receives an uploaded file. We've been having issues with a certain client's request not having a file attached or so the servlet thinks. The upload servlet is a replacement for an old one and we're using the Apache Commons FileUpload library to parse the file from the request. The old code uses the JavaZoom library. The requests client we're having issues with work perfectly fine in the old code.
In order to troubleshoot the problem, I added a bunch of logging to look at the request headers and parts to compare requests from a client that works with the one that doesn't. This is a snippet of how I'm looking at the parts:
Collection<Part> parts = request.getParts();
for(Part part : parts)
{
String partName = part.getName();
log.debug("Part=" + partName);
Collection<String> headerNames = part.getHeaderNames();
for(String headerName : headerNames)
{
String headerValue = part.getHeader(headerName);
log.debug(headerName + "=" + headerValue);
InputStream inputStream = part.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder builder = new StringBuilder();
try
{
for(String line=bufferedReader.readLine(); line!=null; line=bufferedReader.readLine())
{
builder.append(line);
builder.append('\n');
}
}
catch (IOException ignore)
{
// empty
}
finally
{
inputStream.reset();
}
log.debug("InputStream=" + builder.toString());
}
}
All this code works fine and I get the logging I'm expecting. However, this next bit of code doesn't act as expected:
if (isMultipart)
{
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
#SuppressWarnings("rawtypes")
List items = null;
// Parse the request
try
{
items = upload.parseRequest(request);
log.debug("items=" + items);
}
catch (FileUploadException ex)
{
log.warn("Error parsing request", ex);
response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
}
the items variable is empty when it's logged. If I comment out the code for logging the request parts, this bit of code works and the items variable contains the uploaded file.
I can only assume that the act of getting/reading the parts from the request somehow removes them from it and are no longer available for further processing. Is there some way to read them for logging purposes and still retain them in the request for further processing?
The Collection<Part> parts = request.getParts(); is an Sevlet 3.0 API which is replacement for Commons Apache File Upload API.
You should be using only one of the two methods. Both have the support for processing uploaded files and parameters along with it.
Here is the Example for File Upload Using Servlet 3.0
The problem you are facing is because you are invoking this Collection<Part> parts = request.getParts(); request will consume the request input stream. And then you are using Apache Commons API to read the parts again. Because the stream is already read you are seeing no parts are available.
References for Servlet 3.0 File Upload:
Posting Data along with File
Servlet 3.0 Multipart Example
Servlet 3.0 MultipartConfig

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

Resources