Mobile application for upload image from Gallery / Camera , we need to ask run time permission.
If permission granted, we need to use.
const data = new FormData();
data.append("file", {
uri: file_parse_uri,
type: "image/jpeg",
name: file_parse_name,
});
headers: {
Authorization: 'if need',
"Content-Type": "multipart/form-data",
},
i think that you're performing the request wrong, try this instead :
Note : change the pickImage function so that the setUri takes (result.assets[0]) instead of (result.assets[0].uri)
const formBody = new FormData();
formBody.append('image', {
uri: uri.uri,
name: uri.name,
type: uri.type,
});
then instead of passing { image : uri } next to url try to passe this : { body: formBody }
Related
React code for build jsonBlob object
function jsonBlob(obj) {
return new Blob([JSON.stringify(obj)], {
type: "application/json",
});
}
exportFTP = () => {
const formData = new FormData();
formData.append("file", jsonBlob(this.state.ipData));
alert("Logs export to FTP server")
axios({
method: "post",
url: "http://localhost:8080/api/auth/uploadfiles",
data: formData,
headers: {
Accept: "application/json ,text/plain, */*",
"Content-Type": "multipart/form-data",
},
});
};
Spring boot backend that accepts for frontend request
public class UploadFile {
#Autowired
private FTPClient con;
#PostMapping("/api/auth/uploadfiles")
public String handleFileUpload(#RequestParam("file") MultipartFile file) {
try {
boolean result = con.storeFile(file.getOriginalFilename(), file.getInputStream());
System.out.println(result);
} catch (Exception e) {
System.out.println("File store failed");
}
return "redirect:/";
}
I want to figure out when I called the function from the frontend it's working properly but I change the state its doesn't send the object to the backend while the file appears in the directory. if I delete the file then only send it again and save it on the directory.
How I save multiple files while doesn't delete the previous ones
Thank you very much for your time and effort.
"Content-Type": "multipart/form-data",
Don't set the Content-Type yourself when posting a FormData.
The Content-Type needs to contain the boundary value that's generated by a FormData(example: multipart/form-data; boundary=----WebKitFormBoundaryzCZHB3yKO1NSWzsn).
It will automatically be inserted when posting a FormData instance, so leave this header out.
When you append blobs to a formdata then it will default the filename to just "blob"
On the backend you seems to override the file all the time:
con.storeFile(file.getOriginalFilename(), file.getInputStream());
Generate a new unik name if you want to keep all files
of topic but why not go with the fetch api? Smaller footprint. don't require a hole library...
fetch('http://localhost:8080/api/auth/uploadfiles', {
method: 'POST',
body: formData,
headers: {
Accept: 'application/json ,text/plain, */*'
}
})
In React application I used props to pass the file name from a different state and make sure to remove,
"Content-Type": "multipart/form-data",
Main function in React,
exportFTP = ({props from different state}) => {
const formData = new FormData();
formData.append("file", jsonBlob(this.state.ipData),{You can use this parm for pass name});
alert("Logs export to FTP server")
axios({
method: "post",
url: "http://localhost:8080/api/auth/uploadfiles",
data: formData,
headers: {
Accept: "application/json ,text/plain, */*"
},
});
};
And back end code I used same to get the original name then Its appears with the right name.
con.storeFile(file.getOriginalFilename(), file.getInputStream());
Chears !!
I have upgraded react-native to 0.62 and i got the problem of Network error for Android only, iOS works fine.
I use FormData object to populate data formated as
const data = new FormData();
// On Android i add file protocol to file path - file://...
data.append('photos', {
uri: 'file:///data/.../my-image.jpeg',
type: 'image/jpeg',
name: 'my-image.jpeg'
});
and other textual data
data.append('description', 'my long description...');
Does anyone have the problem?
I have tried multiple Android SDKs 27, 28, 29, and got same problem on all :(
The things is if i do not upload images, but only textual data request works just fine :(
Any suggestion welcome :)?
It is happening because of Flipper network plugin.
Comment line number 43 in the file android/app/src/debug/java/com/<yourappname>/ReactNativeFlipper.java
38 NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39 NetworkingModule.setCustomClientBuilder(
40 new NetworkingModule.CustomClientBuilder() {
41 #Override
42 public void apply(OkHttpClient.Builder builder) {
43 // builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44 }
45 });
46 client.addPlugin(networkFlipperPlugin);
In Flipper version 0.39.0 and above this problem was fixed. I've just update Flipper to version 0.40.0 and it working fine.
https://github.com/facebook/flipper/issues/993#issuecomment-619823916
Posting this bec I made it work using react-native-ssl-pinning and react-native-image-crop-picker
FormData
file: {
uri: image.path,
type: image.mime,
name: 'image.jpg',
fileName: 'image.jpg',
size: image.size,
},
and the fetch
fetch(url, {
method: 'POST',
sslPinning: { certs: ['cert'] },
body: {
formData: formData,
},
headers: {
Authorization:
'Bearer Token',
Accept: 'application/json; charset=utf-8',
'Content-type': 'multipart/form-data; charset=UTF-8',
},
})
In android/app/src/main/java/com/{yourProject}/MainApplication.java
comment the below line :
initializeFlipper(this, getReactNativeHost().getReactInstanceManager())
In android/app/src/debug/java/com/{yourProject}/ReactNativeFlipper.java
comment in line 43 :
builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
Code for image upload :
var formData = new FormData();
formData.append('UserId', 'abc#abc.com');
formData.append('VisitId', '28596');
formData.append('EvidenceCapturedDate', '09/10/2019 13:28:20');
formData.append('EvidenceCategory', 'Before');
formData.append('EvidenceImage', {
uri: Platform.OS === 'android' ? `file:///${path}` : `/private${path}`,
type: 'image/jpeg',
name: 'image.jpg',
});
axios({
url: UrlString.BaseUrl + UrlString.imageUpload,
method: 'POST',
data: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
},
})
.then(function (response) {
console.log('*****handle success******');
console.log(response.data);
})
.catch(function (response) {
console.log('*****handle failure******');
console.log(response);
});
I have a form with multiple fileds, which one is a file input. I use axios to upload the file under a separate attribute:
axios.post(ENDPOINT,{
form: formData,
image: image
}, getAuthorizationHeader())
function getAuthorizationHeader() {
return {
headers: {
'Authorization': //...,
'Content-Type': undefined
}
};
}
formData is created like this:
let formData = new FormData();
formData.append('title', values.title);
formData.append('description', values.description);
formData.append('amount', values.amount);
And the image is:
Under the network tab of the Chrome Dev tool, When I look at the request, it looks like this:
As you can see in the screenshot, the file is empty? The CONTENT-TYPE is application/json which is not what I expected. I expected browser to detect the CONTENT-TYPE as multipart/form-data
What is wrong here?
First of all, image should be part of the formData:
formData.append('image', <stream-of-the-image>, 'test.png')
Secondly, formData should be the second parameter of axios.post:
axios.post(ENDPOINT, formData, getAuthorizationHeader())
Last but no least, you should merge formData.getHeaders():
function getAuthorizationHeader() {
return {
headers: Object.assign({
'Authorization': //...,
}, formData.getHeaders())
};
}
Sample code for your reference: https://github.com/tylerlong/ringcentral-js-concise/blob/master/test/fax.spec.js
Problem:
I have a situation where I'd like to upload a file (pdf, image, etc.) to an API Endpoint that accepts one of these types of files. However, the file is located on another web service somewhere. I'm trying to devise a clever solution that will allow me to (a) download the remote file (and store it as bytes in memory or something) then (b) upload that file through the API.
I have jQuery code that demonstrates how to upload a local file using jQuery with no backend code, but I'd like to extend it to allow me to upload something that is stored remotely.
Constraints:
I don't want to use any backend infrastructure on my image uploading page (ie. no php, python, ruby, etc.)
I don't want the end user of my form to need to download the file to their machine and upload the file as a two-step process.
What I've got so far:
I've seen some solutions on SO that kind-of connect the dots here in terms of downloading a file as a bytearray, but nothing that demonstrates how you might upload that.
Download File from Bytes in JavaScript
jQuery-only File Upload to Stripe API*
Keep in mind, Stripe is the example I have, but I'd like to try and replicate this on say Imgur or another API (if I can get this working). Hopefully someone else has some ideas!
$('#fileinfo').submit(function(event) {
event.preventDefault();
var data = new FormData();
var publishableKey = 'pk_test_***';
data.append('file', $('#file-box')[0].files[0]);
data.append('purpose', 'identity_document');
$.ajax({
url: 'https://uploads.stripe.com/v1/files',
data: data,
headers: {
'Authorization': 'Bearer ' + publishableKey,
// 'Stripe-Account': 'acct_STRIPE-ACCOUNT-ID'
},
cache: false,
contentType: false,
processData: false,
type: 'POST',
}).done(function(data) {
$('#label-results').text('Success!');
$('#upload-results').text(JSON.stringify(data, null, 3));
}).fail(function(response, type, message) {
$('#label-results').text('Failure: ' + type + ', ' + message);
$('#upload-results').text(JSON.stringify(response.responseJSON, null, 3));
});
return false;
});
I actually got this working for Stripe by doing this:
https://jsfiddle.net/andrewnelder/up59zght/
var publishableKey = "pk_test_xxx"; // Platform Publishable Key
var stripeAccount = "acct_xxx"; // Connected Account ID
$(document).ready(function () {
$('#file-upload').on('submit', function (e) {
e.preventDefault();
console.log('Clicked!');
var route = $('#file-route').val(); // URL OF FILE
var fname = route.split("/").slice(-1)[0].split("?")[0];
var blob = fetchBlob(route, fname, uploadBlob);
});
});
function fetchBlob(route, fname, uploadBlob) {
console.log('Fetching...')
var oReq = new XMLHttpRequest();
oReq.open("GET", route, true);
oReq.responseType = "blob";
oReq.onload = function(e) {
var blob = oReq.response;
console.log('Fetched!')
uploadBlob(fname, blob);
};
oReq.send();
}
function uploadBlob(fname, blob) {
var fd = new FormData();
fd.append('file', blob);
fd.append('purpose', 'identity_document');
console.log('Uploading...');
$.ajax({
url: 'https://uploads.stripe.com/v1/files',
data: fd,
headers: {
'Authorization': 'Bearer ' + publishableKey,
'Stripe-Account': stripeAccount
},
cache: false,
contentType: false,
processData: false,
type: 'POST',
}).done(function(data) {
console.log('Uploaded!')
}).fail(function(response, type, message) {
console.log(message);
});
}
I am writing an addon in firefox that automatically sends the contents of a canvas to imgur. I have already built a similar extension in chrome, where it works as expected, so I know that the usage of imgurs API is correct. When I use the same approach in the Firefox addon, I always get this response:
{
"data": {
"error": "Image format not supported, or image is corrupt.",
"request": "/3/upload",
"method": "POST"
},
"success": false,
"status": 400
}
This is what I use to extract the image data and send it to the imgur API:
Request({
url: 'https://api.imgur.com/3/upload',
contentType : 'json',
headers: {
'Authorization': 'Client-ID ' + imgurClientID
},
content: {
type: 'base64',
key: imgurClientSecret,
name: 'neon.jpg',
title: 'test title',
caption: 'test caption',
image: getImageSelection('image/jpeg').split(",")[1]
},
onComplete: function (response) {
if (callback) {
callback(response);
} else {
var win = window.open(response['data']['link'], '_blank');
win.focus();
closeWindow();
}
}
}).post();
and this is used to get a selection from a canvas and get the dataurl of that selection:
function getImageSelection(type) {
//Create copy of cropped image
var mainImageContext = mainImage.getContext('2d');
var imageData = mainImageContext.getImageData(selection.x, selection.y, selection.w, selection.h);
var newCanvas = tabDocument.createElement("canvas");
newCanvas.width = selection.w;
newCanvas.height = selection.h;
newCanvas.getContext("2d").putImageData(imageData, 0, 0);
return mainImage.toDataURL(type)
}
I have tried everything: using the dataurl from the original canvas (mainImage), getting the dataUrl without any type, this: .replace(/^data:image\/(png|jpg);base64,/, "");
But imgur keeps complaining about bad format.
In the end, it turned out that the usage of the Request module of the Firefox addon SDK was wrong.
Instead of using contentType to provide the type of the content (like in jquery/ajax), you have to use dataType. See below:
Request({
url: 'https://api.imgur.com/3/upload',
dataType : 'json',
headers: {
'Authorization': 'Client-ID ' + imgurClientID
},
content: {
type: 'base64',
key: imgurClientSecret,
name: 'neon.jpg',
title: 'test title',
caption: 'test caption',
image: getImageSelection('image/jpeg', true)
},
onComplete: function (response) {
response = JSON.parse(response.text);
if (callback) {
callback(response);
} else {
var win = window.open(response['data']['link'], '_blank');
win.focus();
closeWindow();
}
}
}).post();