element ui upload component not sending stream data - upload

Image Upload using el-upload component
I am getting 204 no content response from the server
el-upload(
action="https://s3-us-west-1.amazonaws.com/stage.greenausm.com",
:mulitple="false",
:data="xhrData"
:show-file-list="false", :on-success="handleAvatarSuccess",
:before-upload="beforeAvatarUpload",
)
The request to the server does not have the image data
------WebKitFormBoundaryksB7UzZHz8SWLdPk
Content-Disposition: form-data; name="file"; filename="img.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryksB7UzZHz8SWLdPk--
How can I get the component to send image data

I had a similar problem i worked around it using form data. I set the auto-upload attribute to false then passed a custom http request
<el-upload drag action="" :data="fileList" :http-request="uploadFiles" :auto-upload="false" :multiple="false" >
on the custom function to upload files I created a new formData object and handled it before uploading to the server. Here is an example
uploadFiles() {
//Create new formData object
const fd = new FormData();
//append the file you want to upload
fd.append("file", this.file.raw);
//add other data to the form data object if needed
fd.append("data", this.data);
//send call the api to upload files using axios or any other means
axios.post('http://serveUrl/upload', fd);
},

handleChange(file, fileList){
this.fileList.push(file);
},
:on-change="handleChange"
:file-list="ListFiles"

Related

Rest Assured - Send POST Request (Content-Type : multipart/form-data) with Static JSON Payload and Files to be uploaded

I want to send a POST Request where -
Content Type is "multipart / form-data".
In "Body" section, I have 2 params -> body - {static JSON Payload}, files - {any file, say .log file}
In Rest Assured Code, I am able to get the Static JSON Payload in String format with below code -
String jsonFilePath = "<<Path to JSON File>>/Test_new.json";
String response = given().log().all().header("X-AUTH-TOKEN",res).body(new String(Files.readAllBytes(Paths.get(jsonFilePath)))).
when().post("<<POST RESOURCE URL>>").
then().log().body().assertThat().statusCode(200).extract().response().asString();
When running this code, only with Static JSON Payload, I am getting "415" error code.
Questions -
How can we successfully make this kind of call in Rest Assured?
When I want to upload files as well with this call, how to do that?
You need to use multiPart() methods for uploading files, not body() method. For example:
File json = new File("src/test/resources/test_new.json");
File file = new File("src/test/resources/debug.log");
given().log().all()
.multiPart("files", file)
.multiPart("body", json, "application/json")
.post("your_url");

How do I add a file into a HTTP PUT request calling the Microsoft Graph API?

I am trying to upload a file to a SharePoint Drive by using Microsoft Graph. I am new to REST APIs and Microsoft Graph.
This is what the documentation says:
PUT /me/drive/root:/FolderA/FileB.txt:/content
Content-Type: text/plain
The contents of the file goes here.
Before all of this, I do have my authorization/bearer token and I am able to call the HTTP get but I am not able to upload the file using HTTP PPU.
URL url = new URL(newUrl);
String readLine;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization","Bearer "+ token);
connection.setRequestProperty("Accept","application/json");
This returns java.io.IOException: Server returned HTTP response code: 411 for URL.
I have tried passing it as a binary stream but the request is still failing.
The "type" of the file is determined by the Content-Type header. For some context, the Accept header states the format you expect the response body to use while the Content-Type states the format of your request.
To upload a standard text file, you'll want to use Content-Type: text/plain:
URL url = new URL(newUrl);
String readLine;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization","Bearer "+ token);
connection.setRequestProperty("Accept","application/json");
connection.setRequestProperty("Content-Type","text/plain");

.net core 2 rejects request with 415 when I set Accept to text/csv

When i POST a request to my .net core 2 mvc backend it returns json data.
I want to optionally change the headers as so , which i will then return a csv file of the data for download
'Accept': 'text/csv',
'Content-Type': `text/csv; charset=utf-8`
I set the controller base class with this Produces filter
[Produces("application/json", "text/csv")]
But those headers always cause .net to return 415 Unsupported Media Type
The controller action looks like this
[HttpPost]
public async Task<IActionResult> Post([FromBody] PostArgs args)
You source of problem is Content-Type: text/csv; charset=utf-8 header.
[FromBody] forces MVC middleware to use the input formatter for model binding (I am talking about PostArgs model). And by default, ASP.NET Core registers only one, JSON input formatter. Cause you set Content-Type, middleware cannot use that default formatter (as Content-Type header says that data in request body should be processed as CSV, not JSON) and so it throws 415 Unsupported Media Type error.
... I want to optionally change the headers as so , which i will then return a csv file of the data for download
Actually, it looks like you understand in wrong way what Content-Type header does:
In requests, (such as POST or PUT), the client tells the server what type of data is actually sent.
In other words, you only need to specify the Accept header, cause
The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand. Using content negotiation, the server then selects one of the proposals.
And it is the server then, who uses a Content-Type header in responses to tell the client what the content type of the returned content (in response) actually is.
To return csv data, you return a ContentResult rather than a JsonResult object. This allows you to define the Content-Type:
return new ContentResult("csv-data", "text/csv", 200);
If you want to return a physical file you could return a FileResult object.
By default, the Accepts header isn't enforced. You can enforce it via configuration:
services.AddMvc(config =>
{
config.RespectBrowserAcceptHeader = true;
});
In order to accept additional formats, you'll also need to add InputFormatters:
services.AddMvc(config =>
{
config.RespectBrowserAcceptHeader = true;
config.InputFormatters.Add(new TextInputFormatter())
config.OutputFormatters.Add(new StringOutputFormatter());
});

Post JPEG file using fiddler with other body data

I'm trying to post a jpeg file to a locally developed web service via Fiddler. This would be simple enough, but I also need to include some data alongside the file and can’t quite nail the syntax that fiddler wants. If I click the upload file button and select a file to upload, it replaces my POST body with:
---------------------------acebdf13572468
Content-Disposition: form-data; name="fieldNameHere"; filename="PantheraLeo.jpg"
Content-Type: image/jpeg
<#INCLUDE *C:\temp\PantheraLeo.jpg*#>
---------------------------acebdf13572468—
Now I want to add some additional data:
user=1&album=2&photo=[OUTPUT FROM FILE UPLOAD]
I’ve tried putting this at the start of the body, but when my Node app receives the request, I’m getting a user parameter, an album parameter but no photo.
Any ideas on how I could format this request to get both parameters and the photo uploaded as the photo parameter?
I've also been looking to do something similar myself and stumbled on your question. I've just managed to achieve what I needed after a bit of messing about with Fiddler. Try this:
---------------------------acebdf13572468
Content-Disposition: form-data; name="model"
MyModelInfo
---------------------------acebdf13572468
Content-Disposition: form-data; model="test123"; filename="123.gif"
Content-Type: image/gif
<#INCLUDE *Z:\Downloads\123.gif*#>
---------------------------acebdf13572468--
It would seem that you link the form data being sent up in your request body to the 'acebdf13572468' boundary in the POST info. Provide the Content-Disposition with a key name (in my case 'model') and then the following line represents your actual value for this key. (In my case "MyModelInfo".
Using the above request body I was able to POST up a file as well as some accompanying POST data to my API.
The accepted answer works well. But be warned the extra line after MyModelInfo comes through into the string. Also when copying and pasting in and out of fiddler some lines were corrupted breaking the file.
Note I have named the file param "file" in the fiddler body and in the receiving API function.
This works for me:
---------------------------acebdf13572468
Content-Disposition: form-data; name="PARAM1"
Some text with a line before but not after
---------------------------acebdf13572468
Content-Disposition: form-data; name="file"; filename="filename.jpg"
Content-Type: image/jpeg
<#INCLUDE *C:\local\filename.jpg*#>
---------------------------acebdf13572468--
The data can be received in .net core 2 like this:
[HttpPost]
[Route("AddImage")]
public async System.Threading.Tasks.Task<IActionResult> AddImageAsync(IFormFile file)
{
//f is the same as file
//var f = Request.Form.Files.Count > 0 ? Request.Form.Files[0] : null;
//useful to check the keys
//var additionalProperties = Request.Form.Keys;
if (file != null)
{
try
{
if (Request.Form.TryGetValue("PARAM1", out StringValues p1))
{
var txt = p1.ToString():

Saving an image using node (fs writeStreams) inserts headers into file

I am trying to upload a photo (in a multipart form) from an iOS app, using AFNetworking. I am using node.js for my backend, and almost have it working. The problem is that when I am trying to save the image it is also writing the headers to the file...So all of the images I save have something like this in the beginning (when I open the image in plain text):
--Boundary+9EF923E9CAACB213
Content-Disposition: form-data; name="para"
val
--Boundary+9EF923E9CAACB213
Content-Disposition: form-data; name="afImage"; filename="afImage.jpg"
Content-Type: image/jpeg
The server code I am using is:
uploadIOS: (req, res) ->
tmpfile = variables.uploadsDir + "tempname"
ws = fs.createWriteStream(tmpfile)
req.on 'data', (data) ->
ws.write data
req.on 'end', ->
ws.end()
I can get it working using the express body parser, but would prefer to do it this way if possible. Any ideas how to strip away the headers?
You have to use a multipart-capable parser such as busboy or multiparty.

Resources