Zip File downloaded from ReactJs/Axios is corrupted - django

I'm trying to download a zip file from a Django api and have the user download it. There are two .csv files in the zip.
I am able to download a single .csv files individually, but when I try to download the zip and unzip, I get errors that the zip is corrupted. For sanity check, I am able to send the request via Postman. I am able to successfully download and unzip the file using that.
Here is my code fragment:
axios
.post('http://0.0.0.0:8000/sheets/', data,
{
headers: {
'Content-Type': 'multipart/form-data',
'responseType': 'arraybuffer'
}
})
.then(res => {
console.log(res.data)
const disposition = res.request.getResponseHeader('Content-Disposition')
var fileName = "";
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
fileName = matches[1].replace(/['"]/g, '');
}
let blob = new Blob([res.data], { type: 'application/zip' })
const downloadUrl = URL.createObjectURL(blob)
let a = document.createElement("a");
a.href = downloadUrl;
a.download = fileName;
document.body.appendChild(a);
a.click();

To add to btbam91's reply: responseType has to be part of the config. In the above example:
axios
.post('http://0.0.0.0:8000/sheets/', data,
{
responseType: 'arraybuffer',
headers: {
'Content-Type': 'multipart/form-data',
}
})

The problem was that 'responseType': 'arraybuffer' should not be in "headers."

Related

Flutter S3 Upload AccessDenied

I try to upload the file to S3 but it say AccessDenied, can somebody help me
Here is POST method i have used with http package
var request = http.MultipartRequest("POST", Uri.parse('https://'+bucket+'.s3-'+region+'.'+host));
request.headers.addAll({
'Content-Type': 'multipart/form-data',
});
request.fields['Content-Type']='image/'+typePost;
request.fields['acl']=acl;
request.fields['key']=key;
request.fields['policy']=policy.encode();
request.fields['x-amz-algorithm']='AWS4-HMAC-SHA256';
request.fields['x-amz-credential']=credential;
request.fields['x-amz-date']=longDate;
request.fields['x-amz-signature']=signature.toString();
request.fields['x-amz-security-token']=sessionToken;
request.fields['file']=filePath;
var send = await request.send();
send;
var sendData = await http.Response.fromStream(send);
if (sendData.statusCode==200) {
if (kDebugMode) {
print("Success to upload");
}
}
else {
if (kDebugMode) {
print("Failed to upload");
print(sendData.body);
}
}

Upload attachment in JIRA using MS bot Framework

I'm trying to upload an attachment for Jira ticket using Microsoft Bot framework in Nodejs.
I'm calling the attachment Api in Jira using below code snippet:
const axios = require('axios');
const dotenv = require('dotenv');
const fs = require('fs');
const FormData = require('form-data')
dotenv.config();
class attachmentAPI {
constructor() {
}
async uploadJIRAImage(key) {
let urlString = `https://{jira-site-name}.atlassian.net/rest/api/2/issue/${key}/attachments`;
console.log(urlString);
const credentials = process.env.JiraUsername + ":" + process.env.JiraPassword;
const hash = Buffer.from(credentials).toString('base64');
const Basic = 'Basic ' + hash;
let formData = new FormData();
//Here I want to upload image url from emulator
**let stream = fs.createReadStream("Image.png");**
formData.append('file', stream);
let formHeaders = formData.getHeaders();
let res = await axios.post(urlString, formData, {
headers: {
'Accept': 'application/json',
'Authorization': Basic,
'X-Atlassian-Token': 'nocheck',
...formHeaders
}
});
console.log("Api-Result: ",res)
}
}
exports.attachmentAPI = attachmentAPI;
In this way I can now able to upload the image. As it is located in the same folder locally. But I want to upload an image url from emulator, that need to be attached to JIRA ticket.
emulator image uploaded content is in this format:
{
name: 'SAP-Logo.png',
contentType: 'image/png',
contentUrl: 'http://localhost:12345/v3/attachments/1b864600-fe77-11eb-bc85-b3c9f4256d99/views/original'
}
How do I successfully send the image Url/path in the above code as formdata that attach the image to Jira ticket?
Thanks in advance.

When I use a x-amz-tagging in header it gives 403 forbidden error

Hi I have a working serverless function that uses s3 signedurl to put a file in an s3 bucket using on the Serverless framework that I am trying to migrate to a vercel serverless function using Next.
The function works via the serverless function and Postman, but when I try on Vercel although it generates the signedurl ok but when I try to use it with a "x-amz-tagging"="test" header I get a 403 error. Here is the relevant bit of my code:
//serverless function
const allowCors = fn => async (req, res) => {
res.setHeader('Access-Control-Allow-Credentials', true)
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Methods', 'GET,OPTIONS,PATCH,DELETE,POST,PUT')
res.setHeader(
'Access-Control-Allow-Headers',
'X-CSRF-Token, X-Requested-With, x-amz-tagging, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version'
)
return await fn(req, res)
}
function requestUploadURL(req, res) {
...
}
module.exports = allowCors(requestUploadURL)
//code in app
try {
const config = {
onUploadProgress(progressEvent) {
const percent = Math.round(
(progressEvent.loaded * 100) / progressEvent.total)
adduploadprogress({
file: fileSelectedArray[i].file,
fileType: fileSelectedArray[i].fileType,
myFsize: fileSelectedArray[i].myFsize,
percent,
})
},
headers: {
'Content-Type': fileSelectedArray[i].fileType,
'x-amz-tagging': 'test', // THIS CAUSES 403 ERROR
},
}
const resp1 = await axios.put(
uploadURL,
fileSelectedArray[i].file,
config
)
Any advice gratefully received
For some reason I also need to use Tagging:'' as part of the s3 params in the function being wrapped by the allowCors function. I didn't need to do this before
const { body } = req
const s3Params = {
Bucket: UNIQUEBUCKET,
Key: body.name,
ContentType: body.type,
ACL: 'public-read',
Tagging: '',
}
const uploadURL = s3.getSignedUrl('putObject', s3Params)

Flutter sending a post request to a Django API with a file as the body

I have a Django API where a user is able to upload a file through a post request with the following body:
{
"file": *attached file*
}
In Django, the file is gathered from the request with request.FILES['file']
The request has to be sent from flutter (dart) code. I have tried a few ways, this is the function from my latest attempt which shows an error - because the "file" is not in the correct format.
static void uploadProfilePhoto(File file, String fileId) async {
Uint8List fileBytes = file.readAsBytesSync();
var response = http.post(
globals.baseURL() + "/upload/",
//headers: {"Content-Type": "application/json"},
body: {
"file":base64Encode(fileBytes)
}
).then((v)=>print("v: "+v.body));
}
Any idea in what format the "file" should be sent from flutter? Else is there any other method which might work? Thank you in advance.
in flutter use
import 'dart:convert' as convert;
import 'dart:io';
import 'package:http/http.dart' as http;
#override
Future<Map<String, dynamic>> sendFiletodjango(
{File file,
}) async {
var endPoint = url;
Map data = {};
String base64file = base64Encode(file.readAsBytesSync());
String fileName = file.path.split("/").last;
data['name']=fileName;
data['file']= base64file;
try {
var response = await http.post(endPoint,headers: yourRequestHeaders, body:convert.json.encode(data));
} catch (e) {
throw (e.toString());
}
}
in python django use
from django.core.files.base import ContentFile
file = response.data.get("file")
name = response.data.get("name")
your_file = ContentFile(base64.b64decode(file),name)
model.fileField = your_file
model.save()
You can try multipart/form-data to upload files from Flutter to the Django server using HTTP post request.
From flutter, you can send multipart/form-data request in the below shown way.
Future<Response> uploadFile(File file) async {
Response response;
var uri = Uri.parse(url);
var request = http.MultipartRequest('POST', uri);
request.files.add(await http.MultipartFile.fromPath('file', file.path));
var response = await request.send();
if (response.statusCode == 200 || response.statusCode == 201) {
print('Uploaded!');
}
return response;
}
You can find more about it here Dart MultipartRequest.

Sending binary data from Qt to AngularJs over HTTP

QString path = "my.file";
//QString zipcmd = QString("tar -czf %1.tar.gz %1").arg(path);
//int err = system(zipcmd.toUtf8().data());
// path += ".tar.gz";
QFile file(path);
if (!err && QFile::exists(path) && file.open(QIODevice::ReadOnly)) {
body = file.readAll();
file.close();
status = QHttpResponse::STATUS_ACCEPTED;
}
And there how I process response:
$http({ method: 'GET', url: 'myurl', respponseType: 'blob' })
.then(function success(response) {
var blob = new Blob([response.data],{type: 'application/octet-stream', charset: 'charset=utf-8'});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.download = "myfilename";
a.href = url;
a.click();
});
When I send simple text file every thing is OK.
But when I try to send same file packed to tar.gz I receive incorrect data. I have tried to use toBase64 and atob, change respponseType to arraybuffer and MIME type without any success.
AngularJS 1.4.9 and Qt 5.4. Any help would be appreciated.
Maybe there is another way to transfer files?