I am using pocketbase and svelte.js.
How can I upload pictures to pocketbase via an html input.
<script lang="ts">
import { currentUser, pb } from './pocketbase';
const axios = require('axios').default;
const fileInput = document.getElementById('fileInput');
async function uploadFile() {
axios({
method: 'post',
url: 'http://127.0.0.1:8090/api/collections/images/records',
data: {
image: fileInput.file,
}
});
}
</script>
<form enctype="multipart/form-data" method="post" on:submit={uploadFile}>
<input type="file" name="fileInput" id="fileInput">
<button type="submit">Upload</button>
</form>
Related
Here is my sample code which I got from a website which converts xls to xlsx. It downloads the file immediately after converting it to xlsx, so I want to use that file further as blob. so is there any way to use that file which I will receive from action method using JavaScript?
Thank you!
HTML Code :
<form action="https://v2.convertapi.com/convert/xls/to/xlsx?Secret=...&download=attachment" method="post" enctype="multipart/form-data">
<input type="file" name="File" />
<input type="hidden" name="FileName" value="anyName" />
<input type="submit" value="Convert file"/>
</form>
JavaScript code:
function convert(input){
let obj = {
File : input,
FileName : 'Test'
}
$.ajax({
url: 'https://v2.convertapi.com/convert/xls/to/xlsx?Secret=...&StoreFile=true',
method: 'POST',
headers:{
'content-type' : 'multipart/form-data'
},
body: JSON.stringify(obj),
success : function(res){
console.log(res);
},
error: function(err){
console.log(err.responseText);
}
})
}
you would use javascript's fetch() to upload the file to the conversion endpoint instead of using a form, then you would get the file download as a response, which you can do with what you like.
this question may help you figure out how to upload a file, but you will have to understand a bit of javascript:
How do I upload a file with the JS fetch API?
I tried to upload same way as you mentioned #dqhendricks but didn't worked for me.
when I tried with FormData it worked for me. It would be awesome if we could do it with just JS.
HTML :
<form method="post" enctype="multipart/form-data" id="fileUploadForm">
<input type="file" name="File" />
<input type="hidden" name="FileName" value="newFile" />
<input type="button" id="btnSubmit" value="Convert file"/>
</form>
JS:
$(document).ready(function () {
$("#btnSubmit").click(function (event) {
var form = $('#fileUploadForm')[0];
var d = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: 'https://v2.convertapi.com/convert/xls/to/xlsx?Secret=[Secret]&StoreFile=true',
processData: false,
contentType: false,
cache: false,
data: d,
timeout: 600000,
success: function (res) {
console.log(res);
},
error: function (err) {
console.log(err.responseText);
}
})
});
});
I have a long multistep form. which have text inputs and an upload file option. I'm trying to submit it to PHP with Ajax. I have tried FormData but I'm not sure how to send other select and text input fields.
https://developer.mozilla.org/en-US/docs/Web/API/FormData
How can I do this?
const addListingForm = $('#add-listing-form');
addListingForm.on('submit', function (e) {
console.log('Submitted');
const formData = new FormData(document.getElementById('add-listing-form'));
$.ajax({
url: `${SITE_URL}/private/shared/process`,
type: 'post',
data: formData,
processData: false,
contentType: false,
success: function (resp) {
console.log(resp);
},
error: function (err) {
console.log(err);
},
});
e.preventDefault();
});
<form action="" method="post" enctype="multipart/form-data" id="add-listing-form">
<input type="text" name="title" id="title" class="custom-input" />
<input type="text" name="tagline" id="tagline" class="custom-input" />
<input type="file" name="halal-certificate" class="custom-file-input" id="halal-certificate">
<input type="file" name="list-photos[]" multiple class="custom-file-input" id="list-photos">
<button type="submit">
Submit
</button>
</form>
try this
let title = document.getElementById("title").value;
let firstFile= document.getElementById("list-photos[]").files[0];
let formData = new FormData();
formData.append("file1", firstFile);
formData.append("title", title );
//and add more
or
let title = document.getElementById("title").value;
let firstFile= document.getElementById("list-photos[]").files[0]; // file from input
let req = new XMLHttpRequest();
let formData = new FormData();
formData.append("file1", firstFile);
formData.append("title", title );
req.open("POST", '/upload/image');
req.send(formData);
I am trying to post form data using JS fetch API, also i successfully send data and get response , but got an error in file uploaded my file is not uploaded , and also not get stored filename into database.
<form id="signup">
<label for="myName">Send me your name:</label>
<input type="text" id="myName" name="name" value="abc">
<br>
<label for="userId">your id:</label>
<input type="text" id="userId" name="id" value="123">
<br>
<label for="pic">your photo:</label>
<input id="profile" name="profile" id="profile" type="file">
<br>
<input id="postSubmit" type="submit" value="Send Me!">
</form>
And javascript code
const thisForm = document.getElementById('signup');
const profile = document.getElementById('profile');
thisForm.addEventListener('submit', async function (e) {
e.preventDefault();
const formData = new FormData(thisForm).entries()
formdata.append("profile",profile.files[0]);
const response = await fetch('<?php echo base_url() . 'api/get_subscription' ?>', {
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' },
body: JSON.stringify(Object.fromEntries(formData))
});
const result = await response.json();
console.log(result);
No need to transform to JSON, and no need to use entries() on FormData. Also check the spelling, you wrote formdata which is different than formData.
const thisForm = document.getElementById('signup');
var formData = new FormData(thisForm);
const profile = document.getElementById('profile');
formData.append("profile", profile.files[0]);
const response = await fetch('<?php echo base_url() . 'api/get_subscription' ?>', {
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' },
body: formData
});
For file uploading, you need Content-type multipart/form-data. Or just leave out Content-type, because your browser will probably automatically set this.
This question already has answers here:
How to use FormData for AJAX file upload?
(9 answers)
Closed 3 years ago.
i have this code for upload file to flask.
client side:
<form id="upload-file" method="post" enctype="multipart/form-data">
<fieldset>
<label for="file">Select a file</label>
<input name="file8" type="file">
</fieldset>
<fieldset>
<button id="upload-file-btn" type="button">Upload</button>
</fieldset>
</form>
<script>
$(function() {
$('#upload-file-btn').click(function() {
var form_data = new FormData($('#upload-file')[0]);
$.ajax({
type: 'POST',
url: '/uploading',
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log('Success!');
},
});
});
});
</script>
server side:
#app.route('/uploading', methods = ['POST'])
def uploading():
if request.method == 'POST':
file = request.files['file8']
if file and a
this code upload file and work. How can i send more info to flask same time ?like time = 2020 , age=20 , ...
i find my answer but i cant answer to my question, so i write my ans here:
i use header,send more info like id , ... with user (but this is unsafe):
client side:
<script>
$(function() {
$('#upload-file-btn').click(function() {
var form_data = new FormData($('#upload-file')[0]);
form_data.append('username', 'Chris');
//form_data.append ('id',$('#upload-file')[0]);
console.log(form_data);
$.ajax({
type: 'POST',
url: '/uploading',
data: form_data, headers: {
'Id': 2528,'age':20
},
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log('Success!');
},
});
});
});
</script>
server side:
#app.route('/uploading', methods = ['POST'])
def uploading():
if request.method == 'POST':
file = request.files['file8']
id=request.headers['Id']
age=request.headers['age']
Put the data in the form, then pass the form to new FormData instead of just the file input.
e.g.
<form id="upload-file" method="post" enctype="multipart/form-data">
<fieldset>
<label for="file">Select a file</label>
<input name="file8" type="file">
</fieldset>
<fieldset>
<button id="upload-file-btn">Upload</button>
</fieldset>
<input type=hidden name=time value=2020>
<input type=hidden name=age value=20>
</form>
and
$("form").on("submit", function (e) {
e.preventDefault();
const form = this;
const form_data = new FormData(form);
// etc
});
I am trying to upload multiple files along with normal form data. This thing i have formerly implemented in PHP now i am using to do this in ASP.NET MVC4 in C#.
I have an html form
<form action="/controller/actionane" name="applicationform" class="upload-form" method="post" onsubmit="return false;" enctype="multipart/form-data" id="userform">
<input class="form-control" type="file" class="upload-file" data-max-size="12582912" multiple="multiple" name="attachment[]" value="documents">
<input class="btn btn-success" type="submit" name="submit" onclick="formSubmit()" />
</form>
My Javascript Code with jquery-1.11.1 looks like this:
function formSubmit() {
var form = $("form[name='applicationform']");
var data = new FormData(form[0]);
$.ajax(
{
method: "POST",
url: form.attr("action"),
processData: false, // Don't process the files
contentType: false, cache: false, async: false,
data: data,
success: function (data) {
alert(data);
}
});
}
and my controller looks like this
[HttpPost]
public JsonResult submitApplication(HttpPostedFileBase[] attachment)
{
string fil= "";
foreach (HttpPostedFileBase file in attachment)
{
/*Geting the file name*/
string filename = System.IO.Path.GetFileName(file.FileName);
fil += filename;
/*Saving the file in server folder*/
file.SaveAs(Server.MapPath("~/Images/" + filename));
string filepathtosave = "Images/" + filename;
/*HERE WILL BE YOUR CODE TO SAVE THE FILE DETAIL IN DATA BASE*/
}
return this.Json(fil,JsonRequestBehavior.AllowGet);
}
But this is not passing files to the parameter
Object reference null exception is thrown
What should I do to get this running?
You can try this:
Client Side Code:
<html>
<head>
<title>Upload Example</title>
<script src="~/Scripts/jquery-2.1.0.intellisense.js"></script>
<script src="~/Scripts/jquery-2.1.0.js"></script>
<script src="~/Scripts/jquery-2.1.0.min.js"></script>
<script>
$(document).ready(function () {
$("#Upload").click(function () {
var formData = new FormData();
var totalFiles = document.getElementById("FileUpload").files.length;
for (var i = 0; i < totalFiles; i++)
{
var file = document.getElementById("FileUpload").files[i];
formData.append("FileUpload", file);
}
$.ajax({
type: "POST",
url: '/Home/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("Failed");
}
});
});
});
</script>
</head>
<body>
<input type="file" id="FileUpload" multiple />
<input type="button" id="Upload" value="Upload" />
</body>
</html>
Server Side Code:
Server Side....
public class HomeController : Controller
{
[HttpPost]
public void Upload( )
{
for( int i = 0 ; i < Request.Files.Count ; i++ )
{
var file = Request.Files[i];
var fileName = Path.GetFileName( file.FileName );
var path = Path.Combine( Server.MapPath( "~/[Your_Folder_Name]/" ) , fileName );
file.SaveAs( path );
}
}
}