I am using Spring MVC and this is my method:
/**
* Upload single file using Spring Controller.
*/
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public #ResponseBody ResponseEntity<GenericResponseVO<? extends IServiceVO>> uploadFileHandler(
#RequestParam("name") String name,
#RequestParam("file") MultipartFile file,
HttpServletRequest request,
HttpServletResponse response) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists()) {
dir.mkdirs();
}
// Create the file on server
File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
System.out.println("Server File Location=" + serverFile.getAbsolutePath());
return null;
} catch (Exception e) {
return null;
}
}
}
I need to pass the session id in postman and also the file. How can I do that?
In postman, set method type to POST.
Then select
Body -> form-data -> Enter your parameter name (file according to your code)
On the right side of the Key field, while hovering your mouse over it, there is a dropdown menu to select between Text/File. Select File, then a "Select Files" button will appear in the Value field.
For rest of "text" based parameters, you can post it like normally you do with postman. Just enter parameter name and select "text" from that right side dropdown menu and enter any value for it, hit send button. Your controller method should get called.
The Missing Visual Guide
You must first find the nearly-invisible pale-grey-on-white dropdown for File which is the magic key that unlocks the Choose Files button.
After you choose POST, then choose Body->form-data, then find the File dropdown, and then choose 'File', only then will the 'Choose Files' button magically appear:
Maybe you could do it this way:
Like this :
Body -> form-data -> select file
You must write "file" instead of "name"
Also you can send JSON data from Body -> raw field. (Just paste JSON string)
I got confused after seeing all of the answers, I couldn't find any proper screenshot to bring the Content Type column. After some time, I found it by my own. Hope this will help somebody like me.
Here is the steps:
click on red marked area of postman.
Now check the green marked option (Content Type).
Now change the search content type, in the yellow marked area.
In my case:
invoice_id_ls (key) contains the json data.
documents contains the file data.
placed_amount contains normal text string.
Select [Content Type] from [SHOW COLUMNS] then set content-type of "application/json" to the parameter of json text.
Don't give any headers.
Put your json data inside a .json file.
Select your both files one is your .txt file and other is .json file
for your request param keys.
If somebody wants to send json data in form-data format just need to declare the variables like this
Postman:
As you see, the description parameter will be in basic json format, result of that:
{ description: { spanish: 'hola', english: 'hello' } }
Kindly follow steps from top to bottom as shown in below image.
At third step you will find dropdown of type selection as shown in below image
Body > binary > Select File
If you need like
Upload file in multipart using form data and send json data(Dto object) in same POST Request
Get yor JSON object as String in Controller and make it Deserialize by adding this line
ContactDto contactDto = new ObjectMapper().readValue(yourJSONString, ContactDto.class);
If somebody needed:
body -> form-data
Add field name as array
Use below code in spring rest side :
#PostMapping(value = Constant.API_INITIAL + "/uploadFile")
public UploadFileResponse uploadFile(#RequestParam("file") MultipartFile file,String jsonFileVo) {
FileUploadVo fileUploadVo = null;
try {
fileUploadVo = new ObjectMapper().readValue(jsonFileVo, FileUploadVo.class);
} catch (Exception e) {
e.printStackTrace();
}
If you want to make a PUT request, just do everything as a POST request but add _method => PUT to your form-data parameters.
The way to send mulitpart data which containts a file with the json data is the following, we need to set the content-type of the respective json key fields to 'application/json' in the postman body tab like the following:
You can send both Image and optional/mandatory parameters.
In postman, there is Params tab.
I needed to pass both: a file and an integer. I did it this way:
needed to pass a file to upload:
did it as per Sumit's answer.
Request type : POST
Body -> form-data
under the heading KEY, entered the name of the variable ('file' in my backend code).
in the backend:
file = request.files['file']
Next to 'file', there's a drop-down box which allows you to choose between 'File' or 'Text'. Chose 'File' and under the heading VALUE, 'Select files' appeared. Clicked on this which opened a window to select the file.
2.
needed to pass an integer:
went to:
Params
entered variable name (e.g.: id) under KEY and its value (e.g.: 1) under VALUE
in the backend:
id = request.args.get('id')
Worked!
For each form data key you can set Content-Type, there is a postman button on the right to add the Content-Type column, and you don't have to parse a json from a string inside your Controller.
first, set post in method and fill link API
Then select Body -> form-data -> Enter your parameter name (file according to your code)
If you are using cookies to keep session, you can use interceptor to share cookies from browser to postman.
Also to upload a file you can use form-data tab under body tab on postman, In which you can provide data in key-value format and for each key you can select the type of value text/file. when you select file type option appeared to upload the file.
If you want the Id and File in one object you can add your request object to a method as standard and then within Postman set the Body to form-data and prefix your keys with your request object name. e.g. request.SessionId and request.File.
The steps of uploading a file through postman along with passing some input data is very well discussed in below blog along with the screenshot. In this blog, the api code is written in node js. You can go through it once to have more clarity.
https://jksnu.blogspot.com/2021/09/how-to-create-post-request-with.html
At Back-end part
Rest service in Controller will have mixed #RequestPart and MultipartFile to serve such Multipart + JSON request.
#RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
consumes = {"multipart/form-data"})
#ResponseBody
public boolean yourEndpointMethod(
#RequestPart("properties") #Valid ConnectionProperties properties,
#RequestPart("file") #Valid #NotNull #NotBlank MultipartFile file) {
return projectService.executeSampleService(properties, file);
}
At front-end :
formData = new FormData();
formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
"name": "root",
"password": "root"
})], {
type: "application/json"
}));
See in the image (POSTMAN request):
Click to view Postman request in form data for both file and json
To send image along with json data in postman you just have to follow the below steps .
Make your method to post in postman
go to the body section and click on form-data
provide your field name select file from the dropdown list as shown below
you can also provide your other fields .
now just write your image storing code in your controller as shown below .
postman :
my controller :
public function sendImage(Request $request)
{
$image=new ImgUpload;
if($request->hasfile('image'))
{
$file=$request->file('image');
$extension=$file->getClientOriginalExtension();
$filename=time().'.'.$extension;
$file->move('public/upload/userimg/',$filename);
$image->image=$filename;
}
else
{
return $request;
$image->image='';
}
$image->save();
return response()->json(['response'=>['code'=>'200','message'=>'image uploaded successfull']]);
}
That's it hope it will help you
Related
I have a form in the front-end having multiple entries, i.e name, email, phone and also a file field entry. A Form group is used to group all these elements in the same form in Angular. There is also a corresponding model in Django, (Using Django Rest Framework).
I could not manage to have the file sent to the API, even if the rest of the data is sent correctly and saved on the back-end.
First, I am able to upload the file successfully to Front-end, below I log in the console:
Second, the object I send is something like this:
{"name":"name", "age":49, "email":"email#field.com", "file":File}
The File in the JSON is the same file object displayed in the console above.
I tested my backend with Postman, I was able to succesfully have the file as well as the other data saved. (I believe the problem to be more on the Front-end side ).
Solutions I found for uploading file in Angular used form data (i.e here), these solutions were not convenient as the form consists only of a file, however in my case I have file as well as other data (Form Group).
Another thing I tried that did not work was the following: putting a form Data object with the file in the "file" key of the JSON to be sent. Still, this it did not work.
Also, this is how I upload the file in angular:
public file: File | null = null;
public form: FormGroup;
formData = new FormData();
ngOnInit(){
this.form = this.fb.group({
name: [], [Validators.required]],
age: [],
email: [], [Validators.required]],
file: []});
fileUploadedHandler(file) {
this.file = file;
this.formData.append("file",file, file.name);
this.form.patchValue({file:file}); //this.formData});
this.createDocumentForm.updateValueAndValidity();
console.log(file);}
}
Any propositions to solve this ?
Managed to solve the problem. First I had to use formData instead of formGroup, It was also possible to have multiple fields in formData using append method :
this.formData.append("file",file, file.name);
this.formData.append("name",name);
this.formData.append("age",age);
I had also to revisit the HTTP headers used to submit the form to the API, this was the blocking part.
In my case I had to Remove the 'Content-Type': 'application/json' from the headers. The new working one was:
working_headers = new HttpHeaders({
"Accept": "*/*",
"Authorization": 'Token laksjd8654a6s56a498as5d4a6s8d7a6s5d4a',
});
I'm looking on how to update the ajax configuration dynamically using data from a resource when updating a record. Django REST expects the id at the end of the url and the request method must be type PUT
I've spent some time figuring out how to update the ajax request made by the Datatable Editor plugin. I'm using Django Rest as the backend. This might be useful for some people looking for a similar answer.
Technically you can update the ajax options if the editor object before it sends the request by using the preSubmit Event.
editor.on('preSubmit', (e, request,) =>{
let _url = new URL(window.location.origin + "/" + editor.ajax().url)
if(request.action == 'edit'){
editor.ajax().url = `${_url.protocol}//${_url.host}/api/v1/some-endpoint/${Object.keys(request.data)[0]}/${_url.search}`;
editor.ajax().type = 'PUT'
}
editor.ajax().data = request.data[Object.keys(request.data)]
})
This will update the ajax configuration of the edit request right before it get sent. Django Rest expects a PUT request and the id of the record to be added at the end of the URL. As you can see we grab the id from the data object (Its the first key of the request.data object), and we can also change the type of request to PUT.
I am trying send an image from POSTMAN. I am able to send a message but image is not getting posted.
https://slack.com/api/chat.postMessage
Used POST type headers i am passing token, channel and i have an Image URL but not sure how to send that. Can anyone please help me on this.
There are two alternative approaches on how to send your message to the API endpoint chat.postMessage:
Body as form-urlencoded
Here is how to include an image in a message send as x-www-form-urlencoded:
The image has to be send as part of an attachment by setting the property called image_url.
The attachments are set with the attachments key in the API call, which requires you define your attachments as array of attachment object in JSON.
In addition to the image_url your attachment needs to contain a fallback property, which is used to display a text to the user in case the image can not be displayed.
Your attachments object then looks like this in JSON:
{
"fallback": "this did not work",
"image_url": "https://secure.gravatar.com/avatar/d6ada88a40de8504c6b6068db88266ad.jpg?s=512&d=https%3A%2F%2Fa.slack-edge.com%2F27b6e%2Fimg%2Favatars%2Fsmiley_blobs%2Fava_0016-512.png"
}
Now you have to put that into an array (by adding [] around it) and this is what you get as value for your attachments key:
[{"fallback":"did not work","image_url":"https://secure.gravatar.com/avatar/d6ada88a40de8504c6b6068db88266ad.jpg?s=512&d=https%3A%2F%2Fa.slack-edge.com%2F27b6e%2Fimg%2Favatars%2Fsmiley_blobs%2Fava_0016-512.png"}]
In addition you need to add the keys token, channel, text key to your message. Voila.
Body as JSON
An alternative and probably easier approach is to send your data as JSON instead of x-www-form-urlencoded to the API.
This requires you to send the token in the Auth header and switch to JSON for the body.
To do that in Postman put your token as "Bearer Token" under "Authorization".
In "Body" switch to "raw" and select "JSON".
Then you can define the whole message as follows:
{
"channel": "test",
"text": "Hi there!",
"attachments":
[
{
"fallback": "this did not work",
"image_url": "https://secure.gravatar.com/avatar/d6ada88a40de8504c6b6068db88266ad.jpg?s=512&d=https%3A%2F%2Fa.slack-edge.com%2F27b6e%2Fimg%2Favatars%2Fsmiley_blobs%2Fava_0016-512.png"
}
]
}
Of course you can do the same in your code. Since your are working in JavaScript using JSON would be the natural approach.
Note that not all API methods support sending the body in JSON. Check out this documentation for more info.
I have endpoint which takes few parameters and body as input, and I want to test it in Postman. But, when I input data into 'form-data' section in Postman backend throws error that I am missing body. If I try input data into 'raw' (Text) it complains that I forgot about parameters. How can I combine params and body?
EDIT:
'form-data' section
'raw' section
Parameters for that endpoint are following:
#RequestParam("to") String to,
#RequestParam("subject") String subject,
#RequestBody String content,
#RequestParam("isMultipart") Boolean isMultipart,
#RequestParam("isHtml") Boolean isHtml
For the request params you would add them to the end of the URL rather than in the request body, like you have done in the image.
?to=random#email.com&subject=Testing mailing feature&isMultipart=false&isHTML=true
This can be seen in the Postman UI when you select the Params button, this can be found next to the Send button.
I'm unsure about the string that you need in the request body and in what format the endpoint requires this data.
If it's in a JSON format you could add {"content": "Some new content"} to the raw body and select JSON (application/json) from the dropdown, this will also set the correct request header.
Edit:
The UI has changed slightly since this answer was given. The Paramstab is now placed in a less confusing place.
Suppose all that happens initially in a client swf is a user clicks a hyperlink in a text object of the swf, so this requests a "page" from the server. In response the server just modifies that existing swf in the client browser, by for example (?) invoking public functions of it, and possibly passing in as parameters the name of image or data files which were also downloaded in response to the URL request. The crucial part is that all that can happen initially in the SWF is a URL "page" request. Is this commonly done and if so, how.
Clicking on an hyperlink in AS3 will trigger a TextEvent.LINK event, you can then listen to this event and in your function proceed to call the relevant service which in turn will send you a response which you can use to update your swf data.
Check the docs here for the TextEvent class
http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/
Now, it all depends on what your link is, if it loads an XML ,then you can use the URLLoader class to load the XML data
private function init():void
{
var tf:TextField = new TextField();
tf.htmlText = "<a href='http://example.com/data.xml'>Update Data</a>";
tf.addEventListener(TextEvent.LINK, clickHandler);
addChild(tf);
}
private function clickHandler(e:TextEvent):void
{
trace(e.type); // link
trace(e.text); // http://example.com/data.xml
var loader:URLLoader = new URLLoader();
loader.addEventListener( Event.COMPLETE , dataLoaded );
loader.load( new URLRequest( e.text ) );
}
private function dataLoaded(event:Event):void
{
trace( event.target.data );// xml content
//from here you can then parse the XML & update your swf
}