Spark Java - strange behavior when uploading files - file-upload

In my project I want to try to upload files, here is the part of the code responsible for this:
MultipartConfigElement multipartConfigElement =
new MultipartConfigElement(
"/tmp_files",
avatarSize,
avatarSize,
1024
);
request.raw().setAttribute(
"org.eclipse.jetty.multipartConfig",
multipartConfigElement
);
Part uploadedFile = request.raw().getPart("file");
And a request to upload a file using Idea's http client:
POST http://localhost:8080/users/me/avatar
Content-Type: multipart/form-data; boundary=abcd
Authorization: Bearer {{authToken}}
--abcd
Content-Disposition: form-data; name="file"; filename="test.png"
< /Users/user1/resources/test.png
--abcd--
where test.png is a regular picture.
But when I try to load in this code place:
Part uploadedFile = request.raw().getPart("file");
I get an error:
java.nio.file.NoSuchFileException: /tmp_files/MultiPart11851484240893602177
at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:106)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111)
at java.base/sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:218)
at java.base/java.nio.file.Files.newByteChannel(Files.java:375)
at java.base/java.nio.file.Files.createFile(Files.java:652)
It can be assumed that this error is due to the fact that there are no write permissions to the root of the file system (I'm testing on mac os, under the user).
But if i try to upload another file - which is just a zip file then everything works.
POST http://{{host}}/users/me/avatar
Content-Type: multipart/form-data; boundary=abcd
Authorization: Bearer {{authToken}}
--abcd
Content-Disposition: form-data; name="file"; filename="file123.zip"
< /Users/18493151/develop/icandev/api-gateway/src/main/resources/file123.zip
--abcd--
and no exception in this line:
Part uploadedFile = request.raw().getPart("file");
Why is this happening? Why does the result depend on the file type?
sparkjava version 2.9.4

Related

Parse multipart/form-data response in rust / reqwest

I'm relatively new to rust and using reqwest to fetch a PDF document from a REST API endpoint. The content-type of the response is multipart/form-data; boundary=bc1f6465-6738-4b46-9d9d-b9ae36afa8cb with two parts:
--bc1f6465-6738-4b46-9d9d-b9ae36afa8cb
Content-Disposition: form-data; name="metadata"
Content-Type: application/json
{"documentId":"QkNfRENfSUwwMDEsRTA1OEU3ODQtMDAwMC1DNzY5LTg1MjktMTRFRkI5RTBFNjRF"}
--bc1f6465-6738-4b46-9d9d-b9ae36afa8cb
Content-Disposition: form-data; name="document"; filename=document.pdf
Content-Type: application/pdf
%PDF-1.4
<binary content>
%%EOF
--bc1f6465-6738-4b46-9d9d-b9ae36afa8cb--
I want now to save the PDF document in the 2nd part as a valid PDF file on disk. But the multipart functionality within reqwest seems to create new multipart requests whereas I need to parse a multipart response.
My code to download the file:
use reqwest::{self, header::AUTHORIZATION};
fn main() {
let url = "https://example.com/rest/document/123";
let authorization_header = String::from("Bearer ") + access_token.as_str();
let res = client.get(url)
.header(AUTHORIZATION, &authorization_header)
.send()
.expect("Error calling API");
}
Any hint on how to process the multipart/form-data response is appreciated!

Pdf file uploaded using JMeter but the content is missing in that pdf file means file gets corrupted

I need to upload a pdf file through backend API using JMeter. So for that, I passed a multipart API request. To upload the file I am using BeanShell Preprocessor.
FileInputStream in = new FileInputStream("C:\\Users\\XYZ\\Downloads\\PT_003.pdf");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int i; (i = in.read(buffer)) != -1; ) {
bos.write(buffer, 0, i);
}
in.close();
byte[] binarydata = bos.toByteArray();
bos.close();
vars.put("binarydata", new String(binarydata));
Multipart Request Body :
--AaC07x
Content-Type: application/json; charset=utf-8
{
"token":"a6b8J000000055JQPU",
"flow":"Development"
}
--AaC07x
content-disposition: form-data; name="File"; filename="PT_003.pdf"
Content-Type: application/pdf
Content-Transfer-Encoding: bytecode
${binarydata}
--AaC07x--
Header Manager:-
Content-Type multipart/related;boundary="AaC07x"
File uploaded but content in that pdf file is missing means when I tried to open the uploaded pdf file it's blank/corrupted.
So can you please anyone help me to fix that issue??
It looks like your byte array to string conversion is the problem. Moreover as per JMeter 5.5 you cannot simply send a byte array using HTTP Request sampler as given you put everything into "Body Data" tab it will be treated as a String
Since JMeter 3.1 you should avoid using Beanshell, the recommended scripting language is Groovy
If you have problems coming up with a proper request definition you can just record it using HTTP(S) Test Script Recorder, just make sure that your PT_003.pdf is in JMeter's "bin" folder during both recording and replay

Getting error in file upload using karate api

Could anyone please assist me to file upload functionality using Karate API? I have tried many ways, but getting error message as
"[{"title":"QUERY.BIZ.004","status":500,"detail":"Error in uploading document","timestamp":"2021-12-01T09:04:01.033+01:00"}]"
PAYLOAD DETAILS
metadata: {"key":"FILE_NAME","value":"karate-logo"}
metadata: {"key":"FILE_EXTENSION","value":"jpg"}
metadata: {"key":"TAG","value":"REQUEST"}
metadata: {"key":"DOC_TYP","value":"00008"}
file: (binary)
REQUEST HEADERS
Accept: application/json
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 2368
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary9A1eYQihw4rdVq9f
Below mentioned karate API code which I used in the framework
Given url posturl
And path 'document'
And header id = '1608672'
And header Content-Type = 'multipart/form-data'
And multipart file file = { read: 'classpath:dataDrivenPayload/karate-logo.jpg', filename: 'karate-logo.jpg', contentType: 'image/jpg' }
And multipart field metadata = {"key":"FILE_NAME","value":"karate-logo"}, {"key":"FILE_EXTENSION","value":"jpg"}, {"key":"TAG","value":"REQUEST"}, {"key":"DOC_TYP","value":"00008"}
When method POST
Then status 200
I think the metadata needs to be sent as multiple "parts".
Try something like this:
* url 'https://httpbin.org/anything'
* multipart file metadata = { value: '{"key":"FILE_NAME","value":"karate-logo"}' }
* multipart file metadata = { value: '{"key":"FILE_EXTENSION","value":"jpg"}' }
* method post
* status 200
Otherwise, please use these instructions to troubleshoot, and work with your server-side team if possible: github.com/karatelabs/karate/issues/1645#issuecomment-862502881

.net core web api upload file fail with badrequest

I am trying to upload several files to a web api endpoint with .net core 2.1 web api
this is my controller and the method to upload
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class PagosController : ControllerBase{
[HttpPost("UploadDescuento")]
public async Task<IActionResult> UploadDescuento(IEnumerable<IFormFile> files)
{
return Ok();
}
}
with postman i made a request to de controller but i am getting a badrequest
the first time I thought my request is bad so i do the same request in postman
POST /api/pagos/UploadDescuento HTTP/1.1
Host: localhost:59039
User-Agent: PostmanRuntime/7.16.3
Accept: */*
Cache-Control: no-cache
Postman-Token: 7535f283-89fb-4f86-bbb9-3d78ec302ebe,19a709dd-37c9-48ef-a157-c21f99861260
Host: localhost:59039
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Accept-Encoding: gzip, deflate
Content-Length: 1320022
Connection: keep-alive
cache-control: no-cache
Content-Disposition: form-data; name="files"; filename="/C:/Users/jcpc9/Pictures/0-5616x3744.jpg
------WebKitFormBoundary7MA4YWxkTrZu0gW--,
Content-Disposition: form-data; name="files"; filename="/C:/Users/jcpc9/Pictures/0-5616x3744.jpg
------WebKitFormBoundary7MA4YWxkTrZu0gW--
Content-Disposition: form-data; name="files"; filename="/C:/Users/jcpc9/Pictures/101-2621x1747.jpg
------WebKitFormBoundary7MA4YWxkTrZu0gW--
Content-Disposition: form-data; name="pago"
234235834
------WebKitFormBoundary7MA4YWxkTrZu0gW--
but im getting badrequest
{
"": [
"The input was not valid."
]
}
my solution was remove de attribute ApiController i dont know why the documentation doesnt say to much [https://learn.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-2.2#multipartform-data-request-inference] i dont understend what is the problem
[Produces("application/json")]
[Route("api/[controller]")]
//[ApiController]<<remove this
public class PagosController : ControllerBase
and the method
[HttpPost("UploadDescuento")]
public async Task<IActionResult> UploadDescuento(IEnumerable<IFormFile> files)
if someone know why this propertie "[ApiController]" causing this problema i hope you can explain or at leas an good article
You're not uploading the file. You're just sending the path of the file on the client machine, which the server can't do anything with (unless the server and client machines will always be the same).
Postman does have the option of sending a file properly. See this answer.
You need to select form-data in the body in postman and set up a key "files" as file type example

Multi-Part upload has no payload

I am trying to do a multi-part upload from my javascript application and it works fine in the chrome browser but fails without error when run in electron.
I can't find information, why it fails in electron, but maybe some of you have an idea? :)
var fileContent = new Uint8Array([64,65,66,67]);
var fileBlob = new Blob([fileContent], {type: 'application/octet-stream'});
var data = new FormData();
data.set('file', fileBlob, 'blob.bin');
fetch('http://my.end.point', {
method: 'POST',
body: data
});
When I run that code in Chrome, I can see the 4 bytes payload in the network tab and my end point receives the 4 bytes. If I do the same in electron, the payload in the network tab is empty and the end point receives the multi-part request with the payload missing. I also tried using XMLHttpRequest instead of fetch but that shows exactly the same behavior.
Request Payload from within electron:
------WebKitFormBoundaryNXzPiiAvBttdDATr
Content-Disposition: form-data; name="file"; filename="blob.bin"
Content-Type: application/octet-stream
------WebKitFormBoundaryNXzPiiAvBttdDATr--
Request payload from withon chrome browser:
------WebKitFormBoundarywTEtXn4z3NFt3sAb
Content-Disposition: form-data; name="file"; filename="blob.bin"
Content-Type: application/octet-stream
#ABC
------WebKitFormBoundarywTEtXn4z3NFt3sAb--
Does someone know, why it doesn't work from within electron?