How to Upload and Display File Using Play Framework and jQuery? - javascript

I have one scenario: I am uploading one file at some server location using: https://www.playframework.com/documentation/2.0/JavaFileUpload ,
//Uploading file:
<input type="file" name="fileUpload">
<input type="submit" value="Upload">
And from the below code, I am uploading the above uploaded file and getting/displaying it on my view page like(After clicking the Submit button):
<input type="file" id="inputfile">
<input type="button" value="Submit" id="submitfile">
jQuery:
$("#submitfile").click(function(){
var path1 =$('input[type=file]').val().replace(/C:\\fakepath\\/i, '');//uploaded file names
//adding the Play framework server path for Application to get the image(s) file(s) path
var filespath = '/files/images/'+path1;//giving my uploaded files path here
});
But my requirement is that: I need only one type which does both: accepts/uploads the file at server location and returns/displays the same file path from server location on my view page ? I am struggling for it. Please help me.

This looks like a similar issue to 33163555. That question has the following example:
Edit: Reference 2320069 for support on ajax file uploads & alternatives:
FormData support starts from following desktop browsers versions. IE
10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form enctype="multipart/form-data">
<input type="file" id="file" name="file" />
<input type="submit" id="submit" name="" value="Upload" />
</form>
<script>
$('#submit').click(function (event) {
event.preventDefault();
var file = $('#file').get(0).files[0];
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: 'upload',
data: formData,
type: 'POST',
contentType: false,
processData: false,
beforeSend: function (data) {
alert('Are you sure you want to upload document?');
},
success: function (data) {
//call your jQuery action here
alert('Upload completed: ' + data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ': ' + errorThrown);
}
});
return false;
});
</script>
In your routes you have:
POST /upload controllers.Application.upload()
Where your controller method returns the filepath:
public static Result upload() {
MultipartFormData body = request().body().asMultipartFormData();
FilePart fileP = body.getFile("file");
if (fileP != null) {
File file = fileP.getFile();
//If we want to move from temp
//FileUtils.moveFile(file.getCanonicalPath(), "FileB");
return ok(file.getCanonicalPath());
} else {
return badRequest("Upload Error");
}
}
And you can perform your custom jQuery action in the ajax success callback

Related

upload a form's file and text data to PHP using jQuery and AJAX

Good morning. I'm trying to make the form submission of a message more fluid avoiding the reload of the page for the sending of it. Since the message may be text or image, I need to send both of them to a PHP page for upload. I'm using this code in the html page:
<form id="newmessage" enctype="multipart/form-data">
<textarea form="newmessage" id="messagetext" name="messagetext" ></textarea>
<input type="submit" name="submit" value="send" onclick="return newMessage();">
<input type="file" accept="image/*" id="image" name="image">
</form>
<script>
function newMessage(){
var messagetext = document.getElementById("messagetext").value;
var image = document.getElementById("image").value;
$.ajax({
type:"post",
url:"new_message.php",
data:
{
"messagetext" :messagetext,
"image" :image,
},
cache:false,
success: function(html) {
document.getElementById("messagetext").value = "";
}
});
return false;
}
</script>
As you can see, I'm allowing users to type in the textarea or upload a file. When they submit the form, the newMessage() method is invoked and sends image and messagetext to new_message.php, which process them:
// new_message.php
$messagetext = $_POST["messagetext"];
$image = $_FILES["image"]["tmp_name"];
if((!empty($messagetext) || isset($image))) {
if(!empty($messagetext)) {
// create text message
} else if(isset($image)) {
// create image message
}
}
When I write a text message it works perfectly, but it doesn't send anything if it's image. Maybe the image variable in AJAX is not taking the file properly. I excuse if this question is unclear, but I'm a beginner in StackOverlow and I'm open to edits. Thanks for all replies.
can you try this. you don't need to worry about the file and message in textarea. Make sure you have added jQuery.
$("#newmessage").on("submit", function(ev) {
ev.preventDefault(); // Prevent browser default submit.
var formData = new FormData(this);
$.ajax({
url: "new_message.php",
type: "POST",
data: formData,
success: function (msg) {
document.getElementById("messagetext").value = "";
},
cache: false,
contentType: false,
processData: false
});
return false;
});

How to work with filepond plugin, ajax and php, file name not detected on the server

I am trying to upload file to an xammp server. I'm unable to access the file it uploaded. I doubt on this link server: 'http://localhost/', because when I change it to the name of PHP file that process data on the server side it works.
But also I added another field called username on the form, look below on the code, and I want to combine them on single submit event with Ajax, but I have no idea for this combination.
//initialize file pond with jquery plugin
$('#file').filepond({
allowMultiple: false,
server: 'http://localhost/'
});
//ajax
$("form").on('submit', function(e) {
$.ajax({
url: 'send.php',
type: 'POST',
data: new FormData(this),
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
}).done(function(data) {
if (data.success == false) {
if (data.errors.username) {
$('#username').append('<span class="text-danger">' + data.errors.username + '</span>');
}
if (data.errors.file) {
$('#file').append('<span class="text-danger">' + data.errors.file + '</span>');
}
}
});
e.preventDefault();
});
//my form field between form tag
<form method="POST" enctype="multipart/form-data">
<input type="text" name="username" id="username">
<input type="file" name="file" id="file">
</form>
//php code validate file and name
$errors = [];
if(empty($_FILES['username'])) {
$errors['username'] = 'Enter your name!';
}
//other validation goes here...
if(empty($_FILES['file']['name'])) {
$errors['file'] = 'upload file!';
}
//other validation goes here...
echo json_encode($errors);
EDIT:
I notice that the name attribute in the input type file is not available/removed by the plugin and the input ID is also overwritten every time i load the page,
//example the input look like where the id="filepond--browser-men6qus3m" change every time i load new file
<input class="filepond--browser" type="file" id="filepond--browser-men6qus3m" aria-controls="filepond--assistant-men6qus3m" aria-labelledby="filepond--drop-label-men6qus3m" accept="image/png">
Thus why i get undefine typoerror and the file not attached
You are going to send a FormData with Ajax request. The problem you've mentioned here is that you want to include the file which is attached using FilePond library. Here is my solution to append FilePond files to a FormData:
$(document).ready(function () {
pond = FilePond.create(
document.querySelector('#file'), {
allowMultiple: true,
instantUpload: false,
allowProcess: false
});
$("#upload_form").submit(function (e) {
e.preventDefault();
var fd = new FormData(this);
// append files array into the form data
pondFiles = pond.getFiles();
for (var i = 0; i < pondFiles.length; i++) {
fd.append('file[]', pondFiles[i].file);
}
$.ajax({
url: 'fileupload2.php',
type: 'POST',
data: fd,
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success: function (data) {
// todo the logic
// remove the files from filepond, etc
},
error: function (data) {
// todo the logic
}
}
);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script src="https://unpkg.com/filepond/dist/filepond.min.js"></script>
<script src="https://unpkg.com/jquery-filepond/filepond.jquery.js"></script>
<link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet"/>
<script src="https://unpkg.com/filepond/dist/filepond.js"></script>
<form id="upload_form" method="POST" enctype="multipart/form-data">
<input type="text" name="username" id="username">
<input type="file" name="file" id="file" class="filepond">
<input type="submit" value="Upload"/>
</form>
And on your PHP side, you need can get the files like this:
$errors = [];
if (empty($_POST["username"])) {
$errors['username'] = 'Enter your name!';
}
// check if file is set and uploaded.
if (!isset($_FILES['file']) || $_FILES['file']['error'] == UPLOAD_ERR_NO_FILE) {
$errors['file'] = 'upload file!';
} else {
$filesNum = count($_FILES['file']['name']);
// Looping all files
for ($i = 0; $i < $filesNum; $i++) {
// same the file
move_uploaded_file($_FILES['file']['tmp_name'][$i], $_FILES['file']['name'][$i]);
}
}
// Other validation goes here...
// Return the proper response to the client
// I'll leave this to you
And note that:
I've disabled instantUpload and allowProcess on FilePond to prevent auto uploading and processing.
Your PHP side needs more validation and also it should return proper response to the Ajax.

How to send html form values and file with javascript to webapi [duplicate]

I used this following code to upload file to server, but the file is not uploaded.
Html:
<form id="upload">
<div>
<label for="myFile"></label>
<div>
<input type="file" id="myFile" />
</div>
</div>
<button type="submit">Upload</button>
</form>
Javascript:
// Hook into the form's submit event.
$('#upload').submit(function () {
// To keep things simple in this example, we'll
// use the FormData XMLHttpRequest Level 2 object (which
// requires modern browsers e.g. IE10+, Firefox 4+, Chrome 7+, Opera 12+ etc).
var formData = new FormData();
// We'll grab our file upload form element (there's only one, hence [0]).
var opmlFile = $('#opmlFile')[0];
// If this example we'll just grab the one file (and hope there's at least one).
formData.append("opmlFile", opmlFile.files[0]);
// Now we can send our upload!
$.ajax({
url: 'api/upload', // We'll send to our Web API UploadController
data: formData, // Pass through our fancy form data
// To prevent jQuery from trying to do clever things with our post which
// will break our upload, we'll set the following to false
cache: false,
contentType: false,
processData: false,
// We're doing a post, obviously.
type: 'POST',
success: function () {
// Success!
alert('Woot!');
}
});
// Returning false will prevent the event from
// bubbling and re-posting the form (synchronously).
return false;
});
The Controller is as follows:
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
class UploadController : ApiController
{
public async void Post()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
// We'll store the uploaded files in an Uploads folder under the web app's App_Data special folder
var streamProvider = new MultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/App_Data/Uploads/"));
// Once the files have been written out, we can then process them.
await Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
// Here we can iterate over each file that got uploaded.
foreach (var fileData in t.Result.FileData)
{
// Some good things to do are to check the MIME type before we do the processing, e.g. for XML:
if (fileData.Headers.ContentType.MediaType.Equals("text/xml", StringComparison.InvariantCultureIgnoreCase))
{
// And this is how we can read the contents (note you would probably want to do this asychronously
// but let's try keep things simple for now).
string contents = File.ReadAllText(fileData.LocalFileName);
}
}
});
}
}
The action hit, but the file is not uploaded.
Instead of submit button can you try with normal button -
<form enctype="multipart/form-data">
<label>
Using JQuery
</label>
<input name="file" type="file" id="me" />
<input type="button" id="Upload" value="Upload" />
</form>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
$('#Upload').click(function () {
var formData = new FormData();
var opmlFile = $('#me')[0];
formData.append("opmlFile", opmlFile.files[0]);
$.ajax({
url: 'http://localhost:23133/api/file',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false
});
});
});
</script>
Controller Action -
public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
// Check if files are available
if (httpRequest.Files.Count > 0)
{
var files = new List<string>();
// interate the files and save on the server
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
postedFile.SaveAs(filePath);
files.Add(filePath);
}
// return result
result = Request.CreateResponse(HttpStatusCode.Created, files);
}
else
{
// return BadRequest (no file(s) available)
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
Output -
Your javascript isn't referencing the correct file input control.
You need to change this
var opmlFile = $('#opmlFile')[0];
To this
var opmlFile = $('#myFile')[0];

how to upload file and save to directory? [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet and Ajax?
(4 answers)
Closed 6 years ago.
HTML
<div style="width:200px">
<form action="javascript:_bulkUser();" method="post" enctype="multipart/form-data">
Select File:<input type="file" name="fname"/><br/>
<input type="submit" value="upload"/>
</form>
</div>
js(ajax call)
_bulkUser : function(scope) {
try {
$.ajax({
type : "post",
url : "FileUploadServlet",
success : function(data) {
alert('Sucess');
},
error : function(data) {
console.log(data);
}
});
} catch (e) {
console.log(e);
}
}
Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
System.out.println("working");
MultipartRequest mp = new MultipartRequest(request, "e:/new");
out.print("successfully uploaded");
}
To the point, as of the current XMLHttpRequest version 1 as used by jQuery, it is not possible to upload files using JavaScript through XMLHttpRequest. The common workaround is to let JavaScript create a hidden and submit the form to it instead so that the impression is created that it happens asynchronously. That's also exactly what the majority of the jQuery file upload plugins are doing such as jQuery Form plugin (example here).
Assuming that your JSP with the HTML form is rewritten in such way so that it's not broken when the client has JS disabled (as you have now...), like below:
<form id="upload-form" class="upload-box" action="/Upload" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file1" />
<span id="upload-error" class="error">${uploadError}</span>
<input type="submit" id="upload-button" value="upload" />
</form>
Then it's with help of jQuery Form plugin just a matter of
<script src="jquery.js"></script>
<script src="jquery.form.js"></script>
<script>
$(function() {
$('#upload-form').ajaxForm({
success: function(msg) {
alert("File has been uploaded successfully");
},
error: function(msg) {
$("#upload-error").text("Couldn't upload file");
}
});
});
</script>
As to the servlet side, no special stuff needs to be done here. Just implement it exactly the same way as you would do when not using Ajax: How to upload files to server using JSP/Servlet?
You'll only need an additional check in the servlet if the X-Requested-With header equals to XMLHttpRequest or not, so that you know how what kind of response to return for the case that the client has JS disabled (as of now, it are mostly the older mobile browsers which have JS disabled).
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
// Return ajax response (e.g. write JSON or XML).
} else {
// Return regular response (e.g. forward to JSP).
}
Note that the relatively new XMLHttpRequest version 2 is capable of sending a selected file using the new File and FormData APIs. See also HTML5 File Upload to Java Servlet and sending a file as multipart through xmlHttpRequest.
This code also works fine for me :
$('#fileUploader').on('change', uploadFile);
function uploadFile(event)
{
event.stopPropagation();
event.preventDefault();
var files = event.target.files;
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
postFilesData(data);
}
function postFilesData(data)
{
$.ajax({
url: 'yourUrl',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(data, textStatus, jqXHR)
{
//success
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log('ERRORS: ' + textStatus);
}
});
}
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="fileUploader"/>
</form>

How to upload image with all entered textbox value using AJAX in asp.net MVC 5 without Form or Beging form tag?

I don't want to reload my page so i am using AJAX, here Index.cshtml page for image uploading with text box. This code is currently working but i want to pass data from cshtml page to controller side using of ajax without form tag.
<form class="form-horizontal" id="fc" action="#Url.Action("SaveAcademy", "Academy")" method="post" enctype="multipart/form-data">
#Html.AntiForgeryToken()
<input type="text" class="form-control" onblur="checktxtvalidation(this.id)" name="txtacademyname" id="txtacademyname">
<input type="file" class="form-control" name="fileupload" id="fileupload" multiple="multiple">
<input type="submit" value="submit" id="submit" name="submit" class="btn btn-block btn-primary" />
</form>
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveAcademy(HttpPostedFileBase fileupload, FormCollection fc)
{
....
.... here are some code for inserting data into database
....
}
<input type="file" class="form-control" name="fileupload" id="fileupload" >
it is not need to be in form tags.
<script type="text/javascript">
$('#fileupload').on('change', function (e) {
var files = e.target.files;
var text=$('#txtacademyname').val();
if (files.length > 0) {
var data = new FormData();
data.append("file", files[0]);
data.append("acatext", text);
console.log(data);
$.ajax({
type: "POST",
url: '#Url.Action("SaveAcademy","Academy")',
contentType: false,
processData: false,
data: data,
success: function (data) {
alert(data);
},
error: function () {
}
});
}
});
You can use a button to trigger upload or like my demo just use change event.And if you do not add processData: false to prevent automatic processing , you will get 'Illegal Invocation'.
[HttpPost]
public ActionResult SaveAcademy(HttpPostedFileBase file, string acatext)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var location = Path.Combine(
Server.MapPath("~/Images"), fileName);
file.SaveAs(location);
return Json("File uploaded"+acatext);
}
else
{
return Json("Failed");
}
}
removed [ValidateAntiForgeryToken] if you want it , then you have to add it manually to your ajax header.
EDIT to make it work button click
add button to page <input type="button" value="upload" id="upload" /> ,register click event
<script type="text/javascript">
$('#upload').on('click', function (e) {
var fileform = document.getElementById('fileupload');
var files = fileform.files;
var text=$('#txtacademyname').val();
if (files.length > 0) {
var data = new FormData();
data.append("file", files[0]);
data.append("acatext", text);
console.log(data);
$.ajax({
type: "POST",
url: '#Url.Action("SaveAcademy","Academy")',
contentType: false,
processData: false,
data: data,
success: function (data) {
alert(data);
},
error: function () {
}
});
}
});
</script>
Check this out
http://www.c-sharpcorner.com/UploadFile/b696c4/how-to-upload-and-display-image-in-mvc/
I hope it will be useful for you.

Categories

Resources