get file from filepath in javascript - javascript

I want to send my form(which will have file and name in it) using javascript to the server using http.post request but I am not able to fetch file in javascript. How will i do that i have file path. And i don't want to do this using input tag.
var Form = new FormData();
Form.append("file", file);//this file has to added using path of the file
$http.post(url, Form, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
})
.success(function(d) {
console.log("sucess" + d);
});

Related

Exporting formData from React to Spring boot backend

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 !!

Upload form data fails with axios

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

Corrupted files when uploading to Dropbox via Ajax

I'm trying to use the Dropbox API to send files to a specific Dropbox folder via a web interface using Ajax.
Here is my code:
function UploadFile(token, callback) {
var fileName = $('input[type=file]')[0].files[0].name,
fileData = new FormData($('#file-upload')[0]),
dbxHeaderParams = {
'path': '/' + fileName,
'mode': { '.tag': 'add' },
'autorename': true
};
$.ajax({
url: 'https://content.dropboxapi.com/2/files/upload',
type: 'POST',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/octet-stream',
'Dropbox-API-Arg': JSON.stringify(dbxHeaderParams)
},
data: fileData,
processData: false,
contentType: false,
success: function(result) {
console.log('NICE BRO');
callback();
},
error: function(error) {
console.error(error);
callback();
}
});
}
This code works: files are uploaded to my Dropbox folder and i can open them. They even have the right name and (almost) the right size. But the problem is that they are all corrupted because some lines are added during the process.
Here is an example: if I want to upload a .txt file containing this:
harder better faster stronger
Once uploaded on my Dropbox, it will looks like this:
-----------------------------2308927457834
Content-Disposition: form-data; name="file"; filename="test.txt"
Content-Type: text/plain
harder better faster stronger
-----------------------------2308927457834--
I assume this is why I can't open files like images. I've tried several solutions but none of them can solve this. What am I doing wrong ? Thanks !
Seeing the relevant pieces of the HTML would be useful, but it looks like the issue is that you're supplying a FormData object to the upload call, as opposed to the File.
Try replacing this line:
fileData = new FormData($('#file-upload')[0]),
with this:
fileData = $('input[type=file]')[0].files[0],

Node.js POST request with multipart file as parameter

I need to issue a POST request in Node.js to an API which takes two parameters: 1) "metadata", a string, and 2) "file", a multipart file.
The following is part of the server-side java code:
public ResponseEntity<CmisDocumentDTO> createDocument(
#ApiParam(name = "file", value = "File to be uploaded.", required = true) #RequestParam("file") MultipartFile file,
#ApiParam(name = "metadata", value = "Metadata of the document", required = false) #RequestParam("metadata") String metadata) {
//Calls the service
}
The following is my node.js code calling this request. The file is on my local machine and uses the form-data module:
var FormData = require('form-data');
var form = new FormData();
form.append("metadata", "metadata_string_goes_here");
form.append("file", fs.createReadStream(fileName));
var request = https.request({
method: 'post',
host: 'example.org',
path: '/upload',
"rejectUnauthorized": false,
headers: form.getHeaders()
});
form.pipe(request);
request.on('response', function(res) {
console.log(res.statusCode);
});
When I run this code, an internal service error (code: 500) is returned that says the MultipartFile parameter "file" is not present.
How do I successfully submit a POST request with a multipart file as a parameter?
Thanks!
fileName should be path of the file in local machine
fs.createReadStream(fileName)
In case you have not given absolute path starting with root then Relative paths work, but they are relative to process.cwd(), not the currently executing module.

Trying to submit file via form asynchronously using Angular $http

I am trying to submit a file asynchronously via Angular. This is the HTML:
<form ng-submit="videoSubmit()">
<input id="upl-0" type="file" name="upl" accept="video/ogg, video/mp4, video/webm">
<input type="submit" value='Submit' />
</form>
My Angular code:
$scope.videoSubmit = function() {
var file = document.getElementById('upl-0').files[0];
var formData = new FormData();
console.log(file);
formData.append("upl", file, file.name);
console.log(formData);
console.log(formData.getAll("upl"));
$http({
method: 'POST',
url: "api/asset/upload-test",
data: formData,
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(function(result) {
console.log(result);
});
};
This definitely attaches the file to the formData object because it is displaying the right file data in the console.
Now I want to do something with this on the server, but in the meantime I just want to actually get this working, so this is all that's on the server:
router.post('/api/asset/upload-test', function(req, res) {
console.log(req.data);
console.log(req.body);
});
However somehow the server just doesn't receive the file, and displays undefined for req.data and {} for req.body. Why is this and how can I get this actually working in the same implementation, so without having to encode or decode the file in something like base64 or similar. Thanks.
should be in req.files and in order for that you'll need to use express.bodyParser(). If you use express of course.

Categories