IHP - How to send an attachment as a response from IHP Action? - ihp

How to send an attachment as a response from an IHP action in such a way that after the file is sent, it is deleted from the server.
import System.IO (appendFile)
instance Controller MyController where
action SendFileAction { myData } = do
appendFile "data.txt" myData
-- sendFile "data.txt" "text/plain"
-- delete "data.txt"

There's no way to do this using IHP's renderFile. But you can work around this by reading the file into memory and then sending the response as a plain text. By setting the Content-Disposition header you can make it look like a normal file download in the browser.
import System.IO (appendFile)
instance Controller MyController where
action SendFileAction { myData } = do
appendFile "data.txt" myData
content <- readFile "data.txt"
deleteFile "data.txt"
setHeader ("Content-Disposition", "attachment; filename=\"data.txt\"")
renderPlain content

Related

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

expo how i read an image

I successfully uploaded an image with imagepicker and multer to my folder "uploads/".
I also send the filename back to the client:
res.send({uploadedImage: req.file.path});
// Result:
Object {
"uploadedImage": "uploads\\photo_1619350900261_b1099740-f86c-4809-ae62-0ad973a499c0.jpg",
}
So how can I now read the file or the image? I can put this in a state but there is no url in this image object upload.
To Display the image from response
Use it like this
BaseURL = The URL at which you send post requests (i.e, your Backend Server)
Result.uploadedImage = This you get from the response
So the final uri would be
uri = BaseURL + Result.uploadedImage
It will look Something like this localhost:3000/uploads\\photo_1619350900261_b1099740-f86c-4809-ae62-0ad973a499c0.jpg or 127.0.0.1:3000/uploads\\photo_1619350900261_b1099740-f86c-4809-ae62-0ad973a499c0.jpg
But if you are working on your phone then you might have to replace your BaseURL with your IPv4 address.. This address you can get it from CMD
1.) Open CMD
2.) type ipconfig
3.) Scroll down and look for IPv4 Address..It will look something like this
192.168.100.74
4.) Now uri_to_display = IPv4 Address + : + PORT + Result.uploadedImage

FileSystemApi and writableStream

I'm trying to use the FileSystem API to write an uploaded file on a SPA to a Local sandboxed FileSystem using the FileSystem API.
The File Is uploaded with drop acion and I can get the File object array in the call back.
From the File I can get the ReadableStream calling the stream method (yes, it return only readable sream).
Considering that the uploaded file could be big enough, I would go for a streaming than loading entirely into a blob and then writing into FileSystem api.
So, following the docs the steps are:
get a FileSystem (DOMFileSystem) through the async webkitRequestFileSystem call.
get the prop root that is a FileSystemDirectoryEntry
create a file through getFile (with flag create:true) that returns (async) a FileSystemFileEntry
Now from the FileEntry I can get a FileWriter using createWriter but it is obsolete (in MDN), and in any case it is a FileWriter while I would look to obtain a WritableStream instead in order to use the pipeTo from the uploaded file Handler->ReadableStream.
So, I see that in the console the class (interface) FileSystemFileHandler is defined but I cannot understand how to get an instance from the FileSystemFileEntry. If I can obtain a FileSystemFileHandler I can call the createWritable to obtain a FileSystemWritableFileStream that I can "pipe" with the ReadStream.
Anyone who can clarify this mess ?
references:
https://web.dev/file-system-access/
https://wicg.github.io/file-system-access/#filesystemhandle
https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileEntry
You have the solution in your "references" links at the bottom. Specifically, this is the section to read. You can create files or directories like so:
// In an existing directory, create a new directory named "My Documents".
const newDirectoryHandle = await existingDirectoryHandle.getDirectoryHandle('My Documents', {
create: true,
});
// In this new directory, create a file named "My Notes.txt".
const newFileHandle = await newDirectoryHandle.getFileHandle('My Notes.txt', { create: true });
Once you have a file handle, you can then pipe to it or write to it:
async function writeFile(fileHandle, contents) {
// Create a FileSystemWritableFileStream to write to.
const writable = await fileHandle.createWritable();
// Write the contents of the file to the stream.
await writable.write(contents);
// Close the file and write the contents to disk.
await writable.close();
}
…or…
async function writeURLToFile(fileHandle, url) {
// Create a FileSystemWritableFileStream to write to.
const writable = await fileHandle.createWritable();
// Make an HTTP request for the contents.
const response = await fetch(url);
// Stream the response into the file.
await response.body.pipeTo(writable);
// pipeTo() closes the destination pipe by default, no need to close it.
}

Posting PDF file with form-data: corrupted file?

I'm trying to upload a pdf file with form-data to a server. The upload works but the file gets corrupted for some reason (I can't open the uploaded version). Here's my code:
post_url = 'https://myposturl'
headers = {
'Content-Type':'multipart/form-data; charset=UTF-8; boundary=MyBoundary'
}
with open('./myfile.pdf', 'rb') as f:
body = f'--MyBoundary\r\nContent-Disposition: form-data; name="file"; filename="myfile.pdf"\r\nContent-Type: application/pdf\r\n\r\n{f.read()}\r\n--MyBoundary--\r\n'
res = s.post(post_url, headers = headers, data = body)
I thought it was coming from the \r\n, I tried a replace('\n', '\r\n') on the f.read() output but it didn't work.
Also, when using https://httpbin.org to check the POST request, I get \\\\r\\\\n for each new line in the pdf binary data. I'm wondering if this is normal, maybe that could help.
Thank you in advance for your suggestions.
With requests it can be done a bit easier.
import requests
post_url = 'https://myposturl'
files = {'file': open('./myfile.pdf', 'rb')}
r = requests.post(post_url, files=files)
More docs.
The reason you get corrupted file is probably because you're setting headers and body manually. requests usually sets theses things implicitly, so you should not break this concept and follow official guides.

Invalid 'HttpContent' instance provided. It does not have a 'multipart' content-type header with a 'boundary' parameter

I'm writing a web API that has a post method accepting files uploaded from UI.
public async Task<List<string>> PostAsync()
{
if (Request.Content.IsMimeMultipartContent("form-data"))
{
string uploadPath = HttpContext.Current.Server.MapPath("~/uploads");
var streamProvider = new MyStreamProvider(uploadPath);
await Request.Content.ReadAsMultipartAsync(streamProvider);
return streamProvider.FileData
.Select(file => new FileInfo(file.LocalFileName))
.Select(fi => "File uploaded as " + fi.FullName + " (" + fi.Length + " bytes)")
.ToList();
}
else
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Request!");
throw new HttpResponseException(response);
}
}
Then I post a request for the above action by postman.
I set the content-type header to multipart/form-data
but an error occurred during the execution of action.
here is the error message body :
"Invalid 'HttpContent' instance provided. It does not have a 'multipart' content-type header with a 'boundary' parameter.\r\nParameter name: content"
I went to the postman headers but I found that the request header content type was set to application-json.
You are looking on the response header which is json format and this is ok for you.
Your real problem is with the postman request, so just remove the 'Content-Type: multipart/form-data' entry from request header.
It's enough to upload a file as form-data and send the request.
Look what happen when you set the Content-Type manually vs. when you not:
Postman knows to set both the content type and boundary, since you set only the content type
First: Postman have a bug in handling file-based requests.
You can try adding this to your WebApiConfig.cs it worked for me:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();