I really despair at this problem. I already found some other threads that consider about this problem, but I don't found a solution for me.
I want to upload a mp3 / mp4 file. But with my current solution only pictures are being uploaded.
This question is only about the core functionality of upload a mp3 / mp4 file - I conscious exclude any security checks or kind of this.
PHP:
if(move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES['file']['name']))
{
echo "Successfully Uploaded Images";
}
else
{
echo "Error while uploading";
}
JS:
file = this.files[i];
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function(e) {
//showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("file", file);
}
if (formdata)
{
$.ajax(
{
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(res)
{
document.getElementById("response").innerHTML = res;
}
});
}
EDIT:
I already set the upload_max_filesize to 32 MB.
I got this response from the server:
( ! ) Notice: Undefined index: file in C:\wamp\www\musicplayer_www\public_html\4_upload\upload.php on line 3
Call Stack
# Time Memory Function Location
1 0.0022 134720 {main}( ) ..\upload.php:0
( ! ) Notice: Undefined index: file in C:\wamp\www\musicplayer_www\public_html\4_upload\upload.php on line 3
Call Stack
# Time Memory Function Location
1 0.0022 134720 {main}( ) ..\upload.php:0
EDIT 2:
HTML Form:
<div id="main">
<h1>1. upload track to ftp</h1>
<form method="post" enctype="multipart/form-data" action="upload.php">
<input type="file" name="images" id="images" multiple/>
<button type="submit" id="btn" class="btn btn-default">Upload Files!</button>
</form>
<div id="response"></div>
</form>
</div>
EDIT 3:
In reference to this, there some more limits we have to consider:
post_max_size
upload_max_filesize
memory_limit
So the thought of bluesky is in the right direction.
I think your mp3,mp4 file too large, you can check Maximum allowed size for uploaded file in php.ini, default you can upload file with 2Mb, change upload_max_filesize and restart your server
Use the following:
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
jQuery.ajax({
url: 'upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
Related
I have a file in my view
<form id="upload" enctype="multipart/form-data">
<input type="file" name="fileUpload" id="fileUpload" size="23" />
</form>
and an ajax request
$.ajax({
url: '<%=Url.Action("JsonSave","Survey") %>',
dataType: 'json',
processData: false,
contentType: "multipart/mixed",
data: {
Id: selectedRow.Id,
Value: 'some date was added by the user here :))'
},
cache: false,
success: function (data) {}
});
but there is no file in the Request.Files. Whats wrong with the ajax request?
Upload files using AJAX in ASP.Net MVC
Things have changed since HTML5
JavaScript
document.getElementById('uploader').onsubmit = function () {
var formdata = new FormData(); //FormData object
var fileInput = document.getElementById('fileInput');
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/Upload');
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
return false;
}
Controller
public JsonResult Upload()
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i]; //Uploaded file
//Use the following properties to get file's name, size and MIMEType
int fileSize = file.ContentLength;
string fileName = file.FileName;
string mimeType = file.ContentType;
System.IO.Stream fileContent = file.InputStream;
//To save file, use SaveAs method
file.SaveAs(Server.MapPath("~/")+ fileName ); //File will be saved in application root
}
return Json("Uploaded " + Request.Files.Count + " files");
}
EDIT : The HTML
<form id="uploader">
<input id="fileInput" type="file" multiple>
<input type="submit" value="Upload file" />
</form>
AJAX file uploads are now possible by passing a FormData object to the data property of the $.ajax request.
As the OP specifically asked for a jQuery implementation, here you go:
<form id="upload" enctype="multipart/form-data" action="#Url.Action("JsonSave", "Survey")" method="POST">
<input type="file" name="fileUpload" id="fileUpload" size="23" /><br />
<button>Upload!</button>
</form>
$('#upload').submit(function(e) {
e.preventDefault(); // stop the standard form submission
$.ajax({
url: this.action,
type: this.method,
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data.UploadedFileCount + ' file(s) uploaded successfully');
},
error: function(xhr, error, status) {
console.log(error, status);
}
});
});
public JsonResult Survey()
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
// save file as required here...
}
return Json(new { UploadedFileCount = Request.Files.Count });
}
More information on FormData at MDN
You can't upload files via ajax, you need to use an iFrame or some other trickery to do a full postback. This is mainly due to security concerns.
Here's a decent write-up including a sample project using SWFUpload and ASP.Net MVC by Steve Sanderson. It's the first thing I read getting this working properly with Asp.Net MVC (I was new to MVC at the time as well), hopefully it's as helpful for you.
I have a sample like this on vuejs version: v2.5.2
<form action="url" method="post" enctype="multipart/form-data">
<div class="col-md-6">
<input type="file" class="image_0" name="FilesFront" ref="FilesFront" />
</div>
<div class="col-md-6">
<input type="file" class="image_1" name="FilesBack" ref="FilesBack" />
</div>
</form>
<script>
Vue.component('v-bl-document', {
template: '#document-item-template',
props: ['doc'],
data: function () {
return {
document: this.doc
};
},
methods: {
submit: function () {
event.preventDefault();
var data = new FormData();
var _doc = this.document;
Object.keys(_doc).forEach(function (key) {
data.append(key, _doc[key]);
});
var _refs = this.$refs;
Object.keys(_refs).forEach(function (key) {
data.append(key, _refs[key].files[0]);
});
debugger;
$.ajax({
type: "POST",
data: data,
url: url,
cache: false,
contentType: false,
processData: false,
success: function (result) {
//do something
},
});
}
}
});
</script>
If you posting form using ajax then you can not
send image using $.ajax method,
you have to use classic xmlHttpobject method for saving image,
other alternative of it use submit type instead of button
my problem is while posting multiple forms with ajax in laravel, I am sending the form data without any problem, but I cannot send the file.
File is empty error. I've been dealing with this for 2 days, there is no method I haven't tried, please help me.
Apart from that, I added multipart to the form, but it still didn't work, I'm sharing my codes with you.
Sorry for my bad english.
I want it to upload 2 photos in the normal 4th form until the createProduct3 form, I tried to get them by doing the normal new formData() and I tried otherwise and I couldn't succeed.
It sends it to Laravel server side as [Object File].
My Form
<form class="form" id="createProduct4" method="POST" action="">
<input type="file" class="upload-box-title" id="urun-fotografi" name="urun_fotografi" value="Fotoğraf Seç">
<input type="file" class="upload-box-title" id="urun-dosyasi" name="urun_dosyasi" value="Dosya Seç">
</form>
My blade ajax:
function createProducts()
{
var dataString = $("#createProduct1, #createProduct2, #createProduct3, #createProduct4").serialize();
let photo = document.getElementById("urun-dosyasi").files[0];
let photo2 = document.getElementById("urun-fotografi").files[0];
console.log(photo,photo2);
$.ajax({
url: "{{ route('user.product.create') }}",
type: "POST",
data: dataString+"&urun_dosyasi="+photo+"&urun_fotografi="+photo2,
success: function( data ) {
},
error: function(xhr)
{
console.log(xhr);
}
});
}
Server Function
public function createProduct(Request $request)
{
$file = $request->file('urun_dosyasi');
$file2 = $request->file('urun_fotografi');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$filename2 = $file2->getClientOriginalName();
$extension2 = $file2->getClientOriginalExtension();
echo $filename,$extension."2. doc: ".$filename2.$extension;
}
Use multipart/form-data when your form includes any <input type="file"> elements :
<form ... enctype="multipart/form-data">
Ajax :
var form = $('#createProduct4')[0];
var data = new FormData(form);
$.ajax({
url: "{{ route('user.product.create') }}",
type: "POST",
enctype: 'multipart/form-data',
data: data,
processData: false,
contentType: false,
success: function (data) {
console.log("SUCCESS : ", data);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
I've researched many posts about this and am still experiencing trouble, which is why I decided to post a question about it.
I have an html form with a file input:
<form id='AddFile' action='AddFile.php' method='post' enctype='multipart/form-data'>
<input type='file' id='fileAdd' name='fileAdd'>
Friendly Name: <input type='text' id='friendlyname-Add'>
</form>
I have some JavaScript that prepares the file for upload:
var form = $('AddFile')[0];
var formData = new FormData(form);
$.ajax({
url: "AddFile.php",
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
contentType: false,
processData: false,
success: function(data){
alert("file uploaded!");
...
and PHP that handles the data:
<?php
$uploaddir = 'path';
$uploadfile = $uploaddir . basename($_FILES['fileAdd']['name']);
echo $uploadfile;
if (move_uploaded_file($_FILES['fileAdd']['tmp_name'], $uploadfile)) {
...
}else{
...
}
?>
Typo:
var form = $('AddFile')[0];
^---no #
without a # or ., jquery is looking for a <AddFile> tag, which obviously doesn't exist.
If you had even minimal error handling on the PHP code, you'd have seen that no upload was being performed. There's a ['error'] parameter in $_FILES for a reason:
if($_FILES['fileAdd']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['fileAdd']['error']);
}
I have simple form to ajax-upload files to server.
Here is input event listener:
$(document).on('change', '.js-file', function(event){
sendFile(event);
});
And here is the function that actually uploads the file:
function sendFile (event) {
var files = event.target.files;
var action = '/ajax-upload-files/';
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: action,
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(data){
},
complete: function(data) {
}
});
}
It wors fine with all kinds of files, except those with non-latin characters in the file name, e.g. Максим.jpg
The data is being sent to server, as I see in Chrome network. But when I try to dump $_FILES on server, it seems to be empty.
var_dump($_FILES) //array(0) {}
I don't really understand what's wrong - contentLength of the request header is much smaller then it should be - it looks like file was not appended to form for some reason.
I finally managed to upload non-latin name file.
Have to read it as binary and send as binary.
HTML:
<input class="js-file" name="filename" type="file">
And js
//Handler in input
$(document).on('change', '.js-file', function(event){
var file_name = $(this).attr('name');
var reader = new FileReader();
var f = event.target.files[0],
nameArr = event.target.files[0]['name'].split('.'),
extension = nameArr[nameArr.length-1]; //here we can check if extension is allowed
reader.onload = function(e) {
var contents = e.target.result;
contents = contents.split('base64,')[1]; //we need only encoded part
sendFileAsBinary(file_name, extension, contents);
};
reader.readAsDataURL(f);
});
And sender:
function sendFileAsBinary(file_name, extension, img) {
$.ajax({
url: '/ajax-upload-files/',
type: 'POST',
data: {
name: file_name,
img: img,
extension: extension
},
dataType: 'json',
success: function(data){
},
complete: function(data) {
}
})
}
And php code to decode image:
$name = $this->_getParam('name');
$extension = $this->_getParam('extension');
$computedName = $name . '.' . $extension;
$fileContent = base64_decode($this->_getParam('img'));
file_put_contents($fileContent, $computedName);
here is the code I'm using(your code):
HTML file
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="jquery.min.js"></script>
<script>
$(document).on('change', '#fileToUpload', function(event){
sendFile(event);
});
function sendFile (event) {
var files = event.target.files;
var myAction = 'test.php';
var myData = new FormData();
$.each(files, function(key, value){
myData.append(key, value);
});
$.ajax({
url: myAction,
type: 'POST',
data: myData,
cache: false,
// dataType: 'json',
processData: false,
contentType: false,
success: function(data){
console.log(data);
},
complete: function(data) {
}
});
}
</script>
</head>
<body>
<form action="test.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
test.php
<?php
echo var_dump($_FILES);
?>
result in console.log()
<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=1)</i>
0 <font color='#888a85'>=></font>
<b>array</b> <i>(size=5)</i>
'name' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'Максим.jpg'</font> <i>(length=16)</i>
'type' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'image/jpeg'</font> <i>(length=10)</i>
'tmp_name' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'C:\wamp\tmp\phpE01A.tmp'</font> <i>(length=23)</i>
'error' <font color='#888a85'>=></font> <small>int</small> <font color='#4e9a06'>0</font>
'size' <font color='#888a85'>=></font> <small>int</small> <font color='#4e9a06'>951214</font>
</pre>
so, as you can see, my code uploads file and server can see it. do you have different results on your machine?
I am trying to implement ajax file upload via the HTML5 File API. It's based on Afzaal Ahmad Zeeshan's answer to this question.
I've basically copied the entire code that he wrote, but can't get it to work.
The main aim here is to be able to upload .xls and .xlsx files to the server to work with them later with PHPExcel.
Here's my HTML:
<form class="form-uploadXLS" method="post" action="php/uploadXLS.php" enctype="multipart/form-data">
<div class="form-group">
<div class="col-md-12">
<input type="file" name="xls" class="xls" />
</div>
</div>
<input type="button" value="Upload" class="btn-uploadXLS" />
</form>
<progress></progress>
And here are the jQuery event handlers, just like in the above mentioned answer:
File input onChange event:
$('.xls').on('change', function () {
var file = this.files[0];
var fileName = file.name;
var fileType = file.type;
var fileSize = file.size;
console.log("file name: " + fileName + ", type: " + fileType + ", size: " + fileSize);
});
Upload button's onClick event:
$('.btn-uploadXLS').on('click', function (event) {
event.preventDefault();
console.log("Upload button clicked");
var formData = new FormData($('.form-uploadXLS')[0]);
$.ajax({
url: 'php/uploadXLS.php', //Server script to process data
type: 'POST',
xhr: function () { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: function (stuff) {
console.log("BeforeSend");
console.log(stuff);
},
success: function (data) {
console.log("Success!");
console.log(data);
},
error: function (error) {
console.log("Error!");
console.log(error);
},
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
Edit starts here:
And finally here's my PHP code that prints out the $_FILES array:
if(!empty($_FILES['xls'])) {
echo '<pre>',print_r($_FILES,1),'</pre>';
}
else {
die('POST ÜRES');
}
And here's the result:
Array
(
[xls] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] => 0
)
)
For some reason I can't access the error messages, it only contains the number 4.
What am I doing wrong?
For files you need
$_FILES['xls'] not $_POST
Read Handling file uploads
To get more info just print array
echo '<pre>',print_r($_FILES,1),'</pre>'
Read php - file upload
Ajax File Upload with PHP, HTML5 File API and jQuery