.NET Core - How to upload JSON file? - json

I am trying to upload JSON file in order to read values from it and save them in database, but I have problem with that. Code of my controller looks as following:
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class ImportController : ControllerBase
{
private readonly DatabaseContext dbContext;
public ImportController(DatabaseContext dbContext)
{
this.dbContext = dbContext;
}
[HttpPost]
public IActionResult ImportData(IFormFile file)
{
var content = string.Empty;
using (var reader = new StreamReader(file.OpenReadStream()))
{
content = reader.ReadToEnd();
}
List<UserModel> userObjects = null;
try
{
userObjects = JsonConvert.DeserializeObject<List<UserModel>>(content);
}
catch
{
return BadRequest();
}
foreach (var user in userObjects)
{
UserModel us = new UserModel
{
Username = user.Username,
Password = user.Password
};
dbContext.User.Add(us);
dbContext.SaveChanges();
}
return Ok();
}
}
I'm using Postman to send JSON data, but anytime I try to do it, I get following response:
{"Username":["The input was not valid."]}
when I try to send JSON data as raw->application/json OR
{"":["The input was not valid."]}
when I try to send it by form-data with key called "file" and test.json file as value.
Could you direct me to the right path? I tried to use [FromBody] UserModel user as parameter of my action, but it only allows me to process one JSON string.

You can use [FromBody] IEnumerable<UserModel> users to process many rows. In this case json should look like:
[
{
"userName": "name",
"password": "password",
},
{
"userName": "name1",
"password": "password1",
}
]

You need to standardize your approach one way or another. If you want to accept JSON, then bind to an action param of type List<UserViewModel> with the [FromBody] attribute, and client-side, use JavaScript's FileReader to get the actual content of the upload loaded file and post the content, rather than the file.
If you want to do it by file upload, then you can keep the action as it is, but you'll need to then send your own "JSON" as a file upload as well. This can be achieved by using FormData in JavaScript and creating a Blob manually from your JSON object as a string.
Long and short, whichever path you choose, be uniform about it. There's no way to handle both posting a JSON object and a file upload that happens to be a text file with a .json extension in the same action.

I resolved it... All I had to do was deleting [ApiController] attribute. Having that attribute caused application to didn't visit my ImportData method at all.

Related

How to parse a JSON response for APEX REST Service

I have written a REST class that sets a url as an endpoint to call an API. The API returns a timezone value. The url passes longitude and latitude as a parameter. The response I am getting is a complicated JSON list and I just need the Id value of the Timezone object. This is what I get as a JSON response for a lat/long value I passed:
{
"Version":"2019c",
"ReferenceUtcTimestamp":"2019-12-10T21:14:23.7869064Z",
"TimeZones":[
{
"Id":"America/Los_Angeles",
"Aliases":[
"US/Pacific",
"US/Pacific-New"
],
"Countries":[
{
"Name":"United States",
"Code":"US"
}
],
"Names":{
"ISO6391LanguageCode":"No supported language code supplied",
"Generic":"",
"Standard":"",
"Daylight":""
},
"ReferenceTime":{
"Tag":"PST",
"StandardOffset":"-08:00:00",
"DaylightSavings":"00:00:00",
"WallTime":"2019-12-10T13:14:23.7869064-08:00",
"PosixTzValidYear":2019,
"PosixTz":"PST+8PDT,M3.2.0,M11.1.0",
"Sunrise":"2019-12-10T07:42:22.383-08:00",
"Sunset":"2019-12-10T16:18:49.095-08:00"
},
"RepresentativePoint":{
"Latitude":34.05222222222222,
"Longitude":-118.24277777777777
},
"TimeTransitions":[
{
"Tag":"PST",
"StandardOffset":"-08:00:00",
"DaylightSavings":"00:00:00",
"UtcStart":"2019-11-03T09:00:00Z",
"UtcEnd":"2020-03-08T10:00:00Z"
},
{
"Tag":"PDT",
"StandardOffset":"-08:00:00",
"DaylightSavings":"01:00:00",
"UtcStart":"2020-03-08T10:00:00Z",
"UtcEnd":"2020-11-01T09:00:00Z"
},
{
"Tag":"PST",
"StandardOffset":"-08:00:00",
"DaylightSavings":"00:00:00",
"UtcStart":"2020-11-01T09:00:00Z",
"UtcEnd":"2021-03-14T10:00:00Z"
}
]
}
]
}
Here is my REST Service in APEX:
public class LPP_AccountTimeZone {
public static List<String> getTimeZone(String latitude, String longitude){
Http http = new Http();
HttpRequest req=new HttpRequest();
String url = 'https://atlas.microsoft.com/timezone/byCoordinates/json?subscription-key=XXXXXXXXXXXXXXXXXXXXXXXXXXXX&api-version=1.0&options=all&query='+latitude+','+longitude;
req.SetEndPoint(url);
req.setMethod('GET');
HttpResponse res=http.send(req);
if (res.getStatusCode() == 200) {
List<String> TimeZone = new List<String>();
TimeZoneJSON result = TimeZoneJSON.parse(res.getBody());
for(TimeZoneJSON.TimeZones t : result.timeZones){
System.debug('TimeZone is' + t.Id);
TimeZone.add(t.Id);
}
}
else{
System.debug('The status code returned was not expected: ' + res.getStatusCode() + ' ' + res.getStatus());
}
return TimeZone[0];
}
The response I got with this code (when I ran it in anonymous window) was:
TimeZone is{Aliases=(US/Pacific, US/Pacific-New), Countries=({Code=US, Name=United States}), Id=America/Los_Angeles, Names={Daylight=Pacific Daylight Time, Generic=Pacific Time, ISO6391LanguageCode=en, Standard=Pacific Standard Time}, ReferenceTime={DaylightSavings=00:00:00, PosixTz=PST+8PDT,M3.2.0,M11.1.0, PosixTzValidYear=2019, StandardOffset=-08:00:00, Sunrise=2019-12-12T07:44:13.44-08:00, Sunset=2019-12-12T16:18:47.934-08:00, Tag=PST, WallTime=2019-12-12T11:49:25.0802593-08:00}, Representativ
That is a lot of info. I just want the America/Los_Angeles part which is what Id equals (I have that bold in the response).
Another problem with this code is that it is not returning anything/is void class.
I need t return that value because a trigger is calling that method and will use this value to update a field.
Can anyone please correct my code so that it passes the correct json value and returns the value?
EDIT/UPDATE: The error I am now getting is "Variale does not exist: TimeZone (where the return statement is)
You could use JSON2APEX to easily generate an apex class from your JSON response. Just paste your full response in and click 'Create Apex'. This creates a class that represents your response so that you can easily retrieve fields from it (Keep in mind this will only really work if your response is static meaning the structure and naming stay the same). Have a look through the class that it generates and that will give you an idea of what to do. The class has a parse(String JSON) method which you can call passing in your JSON response to retrieve an instance of that class with your response values. Then it's just a matter of retrieving the fields you want as you would with any object.
Here is how getting the timezone id code would look if you take this route.
(Note: This assumes you keep the name of the class the standard 'JSON2Apex')
if (res.getStatusCode() == 200) {
JSON2Apex result = JSON2Apex.parse(res.getBody());
for(JSON2Apex.TimeZones t: result.timeZones){
System.debug('TimeZone is' + t.id);
tId.add(t);
}
}
To return a value just change void in the method signature to List<String> and return the tId list as follows return tId;

Http post a file data

I have two <input> tag on my client to choose a file. Once the client choose the files (24-bit BMP 640*480), I have to make a http.post so that I could save the imageData of each file and make a http.get when I need it. I tried posting an ImageData object or just an Uint8ClampedArray but I was getting some errors. Now I tried to convert it to base64 and send it but I'm still not getting anything.
This is my http.post:
public submitInfo(): void {
this.http.post("http://localhost:3000/sologame", { "name": this.game.gameName, "image1": this.game.picture }, HTTP_OPTIONS).pipe(
catchError(this.handleError("submitInfo"))).subscribe();
}
This is the error I'm getting now that I'm trying to send a base64 string:
How can I send the data of my image?
There is two way to do it:
Send binary data
onUpload(selectedFile: File) {
this.http.post('api/file-upload', selectedFile).subscribe(...);
}
Send as FormData
onUpload(selectedFile: File) {
const uploadData = new FormData();
uploadData.append('file', selectedFile, selectedFile.name);
this.http.post('api/file-upload', uploadData).subscribe(...);
}

How to handle json in angular4

When I work with a partner to write a website, the backend returns the json format as follows. My front end uses angular4 but I don't know how to use angular4 to process the following json format data. It is a bit worse and there is no json.parse method.
{
"pageNum":1,
"pageSize":4,
"size":1,
"startRow":1,
"endRow":1,
"total":1,
"pages":1,
"list":[
{
"owner":"aa",
"zh_name":"武世伟:广佛06.19-24搭乘ID(正确)",
"push_status":1,
"business":1,
"create_time":1514256602000,
"coupon_status":1,
"monitor_status":1,
"model_status":3,
"message_status":1,
"monitor_end_time":1514256602000,
"random_group":1,
"name":"p_pm_passenger_taxi_20171226105028119",
"calc_way":1,
"monitor_start_time":1514256602000,
"id":11,
"model_num":8837
}
],
"prePage":0,
"nextPage":0,
"isFirstPage":true,
"isLastPage":true,
"hasPreviousPage":false,
"hasNextPage":false,
"navigatePages":8,
"navigatepageNums":[
1
],
"navigateFirstPage":1,
"navigateLastPage":1,
"status":200,//状态200正常,400 错误
"firstPage":1,
"lastPage":1
}
Angular indeed provides you with a JSON.parse()-method which actually derives from JavaScript. You can convert your server response json into an object.
// in your component
private object;
Then you can access the content. For example:
// call this method after having received your json
private show(data: any): void {
this.object = JSON.parse(data);
console.log(this.object.pageNum);
console.log(this.object.total);
console.log(this.object.list[0].zh_name);
}

Codenameone how to add multiple JSON subentries in a POST query

I have a REST webservice which allows me to upload user details in JSON format via a POST request. It looks like I can do this using
post.addArgument("Name",entry.get("Name").toString());
post.addArgument("JobRole",entry.get("JobRole").toString());
"entry" is an ArrayList < MapString, Object>
As you can see in the below JSON I also have the option of sending multiple entries per user (in this case address details) as in this JSON example:
{
"Name":"Fred Flintstone",
"JobRole":"Quarry worker",
"Address":[
{
"Address1" :"Boulder House",
"Address2" :"Rock Way",
"Address3" :"Rock City"
}
]
}
I have tried using
post.addArgumentArray("Address",entry.get("Address1").toString,entry.get("Address2"))
to combine the entries for the user under Address but I get "400: Bad Request" returned. So how do I add multiple entries like this to my request?
Regards
Those are POST style arguments and they are added as regular HTTP arguments not as JSON (it's like submitting a form in HTML).
What you are looking for is something like:
ConnectionRequest cr = new ConnectionRequest(url, true) {
protected void buildRequestBody(OutputStream os) throws IOException {
// snipped this but you should get the rest...
os.write("{\"Name\":\"Fred Flintstone\",\"JobRole\":\"Quarry worker\", ...");
}
};
Alternatively you can use the new terse REST API:
Map<String, Object> jsonData = Rest.post(myUrl).body(bodyValueAsString).getAsJsonMap();

Posting a File and Associated Data to a RESTful WebService preferably as JSON

In an application I am developing RESTful API and we want the client to send data as JSON. Part of this application requires the client to upload a file (usually an image) as well as information about the image.
I'm having a hard time tracking down how this happens in a single request. Is it possible to Base64 the file data into a JSON string? Am I going to need to perform 2 posts to the server? Should I not be using JSON for this?
As a side note, we're using Grails on the backend and these services are accessed by native mobile clients (iPhone, Android, etc), if any of that makes a difference.
I asked a similar question here:
How do I upload a file with metadata using a REST web service?
You basically have three choices:
Base64 encode the file, at the expense of increasing the data size by around 33%, and add processing overhead in both the server and the client for encoding/decoding.
Send the file first in a multipart/form-data POST, and return an ID to the client. The client then sends the metadata with the ID, and the server re-associates the file and the metadata.
Send the metadata first, and return an ID to the client. The client then sends the file with the ID, and the server re-associates the file and the metadata.
You can send the file and data over in one request using the multipart/form-data content type:
In many applications, it is possible for a user to be presented with
a form. The user will fill out the form, including information that
is typed, generated by user input, or included from files that the
user has selected. When the form is filled out, the data from the
form is sent from the user to the receiving application.
The definition of MultiPart/Form-Data is derived from one of those
applications...
From http://www.faqs.org/rfcs/rfc2388.html:
"multipart/form-data" contains a series of parts. Each part is
expected to contain a content-disposition header [RFC 2183] where the
disposition type is "form-data", and where the disposition contains
an (additional) parameter of "name", where the value of that
parameter is the original field name in the form. For example, a part
might contain a header:
Content-Disposition: form-data; name="user"
with the value corresponding to the entry of the "user" field.
You can include file information or field information within each section between boundaries. I've successfully implemented a RESTful service that required the user to submit both data and a form, and multipart/form-data worked perfectly. The service was built using Java/Spring, and the client was using C#, so unfortunately I don't have any Grails examples to give you concerning how to set up the service. You don't need to use JSON in this case since each "form-data" section provides you a place to specify the name of the parameter and its value.
The good thing about using multipart/form-data is that you're using HTTP-defined headers, so you're sticking with the REST philosophy of using existing HTTP tools to create your service.
I know that this thread is quite old, however, I am missing here one option. If you have metadata (in any format) that you want to send along with the data to upload, you can make a single multipart/related request.
The Multipart/Related media type is intended for compound objects consisting of several inter-related body parts.
You can check RFC 2387 specification for more in-depth details.
Basically each part of such a request can have content with different type and all parts are somehow related (e.g. an image and it metadata). The parts are identified by a boundary string, and the final boundary string is followed by two hyphens.
Example:
POST /upload HTTP/1.1
Host: www.hostname.com
Content-Type: multipart/related; boundary=xyz
Content-Length: [actual-content-length]
--xyz
Content-Type: application/json; charset=UTF-8
{
"name": "Sample image",
"desc": "...",
...
}
--xyz
Content-Type: image/jpeg
[image data]
[image data]
[image data]
...
--foo_bar_baz--
Here is my approach API (i use example) - as you can see, you I don't use any file_id (uploaded file identifier to the server) in API:
Create photo object on server:
POST: /projects/{project_id}/photos
body: { name: "some_schema.jpg", comment: "blah"}
response: photo_id
Upload file (note that file is in singular form because it is only one per photo):
POST: /projects/{project_id}/photos/{photo_id}/file
body: file to upload
response: -
And then for instance:
Read photos list
GET: /projects/{project_id}/photos
response: [ photo, photo, photo, ... ] (array of objects)
Read some photo details
GET: /projects/{project_id}/photos/{photo_id}
response: { id: 666, name: 'some_schema.jpg', comment:'blah'} (photo object)
Read photo file
GET: /projects/{project_id}/photos/{photo_id}/file
response: file content
So the conclusion is that, first you create an object (photo) by POST, and then you send second request with the file (again POST). To not have problems with CACHE in this approach we assume that we can only delete old photos and add new - no update binary photo files (because new binary file is in fact... NEW photo). However if you need to be able to update binary files and cache them, then in point 4 return also fileId and change 5 to GET: /projects/{project_id}/photos/{photo_id}/files/{fileId}.
I know this question is old, but in the last days I had searched whole web to solution this same question. I have grails REST webservices and iPhone Client that send pictures, title and description.
I don't know if my approach is the best, but is so easy and simple.
I take a picture using the UIImagePickerController and send to server the NSData using the header tags of request to send the picture's data.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"myServerAddress"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:UIImageJPEGRepresentation(picture, 0.5)];
[request setValue:#"image/jpeg" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"myPhotoTitle" forHTTPHeaderField:#"Photo-Title"];
[request setValue:#"myPhotoDescription" forHTTPHeaderField:#"Photo-Description"];
NSURLResponse *response;
NSError *error;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
At the server side, I receive the photo using the code:
InputStream is = request.inputStream
def receivedPhotoFile = (IOUtils.toByteArray(is))
def photo = new Photo()
photo.photoFile = receivedPhotoFile //photoFile is a transient attribute
photo.title = request.getHeader("Photo-Title")
photo.description = request.getHeader("Photo-Description")
photo.imageURL = "temp"
if (photo.save()) {
File saveLocation = grailsAttributes.getApplicationContext().getResource(File.separator + "images").getFile()
saveLocation.mkdirs()
File tempFile = File.createTempFile("photo", ".jpg", saveLocation)
photo.imageURL = saveLocation.getName() + "/" + tempFile.getName()
tempFile.append(photo.photoFile);
} else {
println("Error")
}
I don't know if I have problems in future, but now is working fine in production environment.
FormData Objects: Upload Files Using Ajax
XMLHttpRequest Level 2 adds support for the new FormData interface.
FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.
function AjaxFileUpload() {
var file = document.getElementById("files");
//var file = fileInput;
var fd = new FormData();
fd.append("imageFileData", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", '/ws/fileUpload.do');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert('success');
}
else if (uploadResult == 'success')
alert('error');
};
xhr.send(fd);
}
https://developer.mozilla.org/en-US/docs/Web/API/FormData
Since the only missing example is the ANDROID example, I'll add it.
This technique uses a custom AsyncTask that should be declared inside your Activity class.
private class UploadFile extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// set a status bar or show a dialog to the user here
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// progress[0] is the current status (e.g. 10%)
// here you can update the user interface with the current status
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
private String uploadFile() {
String responseString = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/upload-file");
try {
AndroidMultiPartEntity ampEntity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
// this trigger the progressUpdate event
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File myFile = new File("/my/image/path/example.jpg");
ampEntity.addPart("fileFieldName", new FileBody(myFile));
totalSize = ampEntity.getContentLength();
httpPost.setEntity(ampEntity);
// Making server call
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200) {
responseString = EntityUtils.toString(httpEntity);
} else {
responseString = "Error, http status: "
+ statusCode;
}
} catch (Exception e) {
responseString = e.getMessage();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
// if you want update the user interface with upload result
super.onPostExecute(result);
}
}
So, when you want to upload your file just call:
new UploadFile().execute();
I wanted send some strings to backend server. I didnt use json with multipart, I have used request params.
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public void uploadFile(HttpServletRequest request,
HttpServletResponse response, #RequestParam("uuid") String uuid,
#RequestParam("type") DocType type,
#RequestParam("file") MultipartFile uploadfile)
Url would look like
http://localhost:8080/file/upload?uuid=46f073d0&type=PASSPORT
I am passing two params (uuid and type) along with file upload.
Hope this will help who don't have the complex json data to send.
You could try using https://square.github.io/okhttp/ library.
You can set the request body to multipart and then add the file and json objects separately like so:
MultipartBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("uploadFile", uploadFile.getName(), okhttp3.RequestBody.create(uploadFile, MediaType.parse("image/png")))
.addFormDataPart("file metadata", json)
.build();
Request request = new Request.Builder()
.url("https://uploadurl.com/uploadFile")
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
logger.info(response.body().string());
#RequestMapping(value = "/uploadImageJson", method = RequestMethod.POST)
public #ResponseBody Object jsongStrImage(#RequestParam(value="image") MultipartFile image, #RequestParam String jsonStr) {
-- use com.fasterxml.jackson.databind.ObjectMapper convert Json String to Object
}
Please ensure that you have following import. Ofcourse other standard imports
import org.springframework.core.io.FileSystemResource
void uploadzipFiles(String token) {
RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000)
def zipFile = new File("testdata.zip")
def Id = "001G00000"
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
form.add("id", id)
form.add('file',new FileSystemResource(zipFile))
def urld ='''http://URL''';
def resp = rest.post(urld) {
header('X-Auth-Token', clientSecret)
contentType "multipart/form-data"
body(form)
}
println "resp::"+resp
println "resp::"+resp.text
println "resp::"+resp.headers
println "resp::"+resp.body
println "resp::"+resp.status
}