Upload file to j2ee spring, file is null - javascript

I'm trying to upload a file to my J2eE spring backend. But if I set file required then it does not recognize, so therefor i conclude that it must be the way I try to send it from the front end.
HTML definition:
<form id="filesUploadForm" action="spring/uploadFile" method="post" enctype="multipart/form-data">
<input class="std" id="file" type="file" name="choose">
</form>
Javascript: (Which is triggered from another button)
function uploadFile() {
var url = 'spring/uploadFile';
var formData = $('#filesUploadForm').serialize();
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function() {
console.log('upload complete');
};
xhr.send(formData);
}
If it is relevant: here is the Java code:
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public void uploadFile(#RequestParam(value = "file", required = false) MultipartFile multipartFile) {
String fileName = multipartFile.getOriginalFilename();
System.out.println(fileName);
}

I think you need to change the parameter name in your Java code:
#RequestParam(value = "choose", required = false)

Related

How to export a csv file after uploading a excel file and manipulating the data using post request in ajax java?

My problem is:
I am uploading a excel file first. After reading the file and manipulating the data, i need to generate a csv and export the same on click of the submit button.
Below is my html/javascript code:
<div>Please upload the Excel File</div>
<form method="POST" id="fileUploadForm" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input type="submit" value="Submit" id = "defaultSubmit" />
</form>
Below is the Ajax Request:
$(document).ready(function() {
$("#defaultSubmit").click(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
// $("#fileupload").click();
// Get form
var form = $('#fileUploadForm')[0];
// Create an FormData object
var data = new FormData(form);
$.ajax({
url : "/uploadExcelFiles",
type: "POST",
enctype: 'multipart/form-data',
data: data,
processData: false,
contentType: false,
success : function(data) {
},
error : function(data) {
}
});
return false;
});
Now Below is the java code:
#RequestMapping("/uploadExcelFiles")
public void readExcelFile(HttpServletResponse response, #RequestParam("file") MultipartFile uploadedFile) {
File file = new File(uploadedFile.getOriginalFilename());
List<EmployeeData> empData = new ArrayList<>();
empData = blAttendanceService.readFile(file);
TreeMap<Object, Object> map = blAttendanceService.calculateWorkingSecondsForEmployeeInDay(empData);
List<EmployeeChartsModel> list = new LinkedList<>();
for (Entry<Object, Object> ent : map.entrySet()) {
EmployeeChartsModel ehd = new EmployeeChartsModel();
long seconds = (long) ent.getValue();
double dailyHoursSpent = (double)seconds/3600;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-YYYY");
System.out.println("Date::: " + sdf.format((Date)ent.getKey()) + " ::::::Hours:::: " + dailyHoursSpent);
ehd.setEmployeeDate(sdf.format((Date)ent.getKey()));
ehd.setDailyHoursSpent(dailyHoursSpent);
list.add(ehd);
}
String filename = "DailyAttendanceRecord.csv";
response.setContentType("text/csv");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"");
try {
StatefulBeanToCsv<EmployeeChartsModel> writer = new StatefulBeanToCsvBuilder<EmployeeChartsModel>(response.getWriter())
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.withOrderedResults(false)
.build();
writer.write(list);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
EmployeeChartsModel is a class for csv Model.
I am not getting any error in the code. Just the file is not exported. Also, If i read the file manually from my location and direct hit the url of this method, the file is successfully exported. But i am unable to do so through ajax post request.
Kindly suggest the changes so as to export the csv file using this ajax post request.
I am using Java, Spring Boot, Html, Javascript in my code.

How to upload a .mp3 file in HTML / Javascript and send to Java backend

We're trying to upload a song (.mp3) file from a JSP frontend written in HTML / Javascript. We need to upload to our Java backend using websockets. Does anyone have any suggestions on how we would could go about doing this?
Currently we are doing something like this on our JSP file:
<h1>Please Choose a Song file</h1>
<form name = "JSONUploadForm">
<input type = "file" name="file" accept = ".mp3"/> <br/>
<input type = "button" value = "Click to upload!" name = "button" onClick = "submitSong();"/>
</form>
Then we have our javascript function submitSong()
function submitSong(){
var songStuffs = document.getElementById("file");
console.log(songStuffs); --> we get "null" here
sendMessage(songStuffs);
alert("song sent");
}
function sendMessage(val, string) {
socket.send(string);
return false;
}
Also, here is our connect to server function. However, this functions correctly.
function connectToServer() {
socket = new
WebSocket("ws://localhost:8080/Project/socket");
socket.onopen = function(event) {
console.log("connected!");
}
You can also see our server side (.java file):
#OnMessage
public void onMessage(String message, Session session) throws IOException, EncodeException {
FileWriter fw = new FileWriter(new File(songName + ".mp3"));
fw.write(song);
BufferedReader fr = new BufferedReader(new FileReader(songName + ".mp3"));
String data = fr.readLine();
System.out.println("Song: " + data); --> Here we get "song: null"
}
Any suggestions would be greatly appreciated!
In your code you have an error
"var songStuffs = document.getElementById("file");"
Your file input without id.
this will work "var songStuffs = document.querySelector("[name=file]");"
I prefer using querySelector, because it mo flexeble and works exactly like jquery query selectors)))
You do not need any form, for upload files.
Please read this article https://www.html5rocks.com/en/tutorials/websockets/basics/,
it will be useful for you (search words "blob" at the page)
Html
<input id="file" type = "file" name="file" accept = ".mp3"/>
Code
var fileInput = document.querySelector("#file");
fileInput.addEventListener("change",function(){
connection.send(fileInput.files[0]);
});
If you need to send file and fields, you have 3 variants
create JSON {"field1":"value1","field2":"value1",
"file":"base64"}
manualy create formdata and parse form data at the
server with some webform stuff (example
https://stackoverflow.com/a/47279216/5138198)
Firstly send JSON
data, secondly send a file
Try with this, If you have to upload file you should add enctype in form.
<form enctype="multipart/form-data">
<input type = "file" name="file" id="song" accept = ".mp3"/>
</form>
Update:
You can use simply WebSocketFileTransfer plugin to send your file. This plugin helps in with many features like Auth, progress status, file/blob compatibility.
var songStuffs = document.getElementById("song").files[0];
var transfer = new WebSocketFileTransfer({
url: 'ws://ip:port/path/to/upload_web_socket_server',
file: songStuffs,
progress: function(event) {
// Update the progress bar
},
success: function(event) {
// Do something
}
});
transfer.start();

AJAX: Asynchronously posting a file to a server

I want to post a file to server asynchronously without posting the form. I have the following code:
var fileInput = document.getElementById('FileInput');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file, file.name);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://servername/controllername/AnalyseFile', true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.send(formData);
However, when the method is executed on the server, the post body contains no files. The following is from ASP.NET MVC4:
[HttpPost]
public JsonResult AnalyseFile()
{
int filesCount = Request.Files.Count;
if(filesCount == 0) { throw new Exception('no files...'); }
// do stuff
}
The Files collection contains no files and I can't figure out why. Any help appreciated.
In the View, you can do:
<form>
<input name="input1" id="input1"/>
<input name="input2" id="input2"/>
<input name="input3" id="input3"/>
...
<input id="SelectedFile" name="SelectedFile" type="file"/>
</form>
And Javascript:
function AttLogic(_url, _data, _callback) {
$.ajax({
url: _url,
type: 'POST',
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { }
return myXhr;
},
data: _data,
cache: !1,
success: _callback,
contentType: !1,
processData: !1
});
}
function FormDataCustom(f) {
var __frm = jQuery(f), data = new FormData(f);
$(':disabled[name]', __frm).each(function () {
data.append(this.name, $(this).val());
});
return data;
}
function SaveLogic(){
var dt = FormDataCustom(document.forms[0]);
AttLogic(yourUrl, dt, function (r) {
//do something here
});
}
In the Controller:
public ActionResult Save(parameter1,parameter1,..., List<HttpPostedFileBase> SelectedFile)
{
//do something here
}
You will need to read the MultiPartFormData from the Request.
As per this post:
Your method will look something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Some.Namespace
{
public class SomeController : ApiController
{
[HttpPost]
public async Task<JsonResult> AnalyseFile()
{
if (!Request.Content.IsMimeMultipartContent())
{
//If not throw an error
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider("c:\\tmp\\uploads");
// Read the MIME multipart content using the stream provider we just created.
IEnumerable<HttpContent> bodyparts = await Request.Content.ReadAsMultipartAsync(streamProvider);
// Get a dictionary of local file names from stream provider.
// The filename parameters provided in Content-Disposition header fields are the keys.
// The local file names where the files are stored are the values.
//depending on your version of .net, this might have been changed to FileData instead.
// see: https://msdn.microsoft.com/en-us/library/system.net.http.multipartformdatastreamprovider(v=vs.118).aspx
IDictionary<string, string> bodyPartFileNames = streamProvider.BodyPartFileNames;
//rest of code here
}
}
I haven't tested the above code, but it should point you in the right direction.
Also have a look at How To Accept a File POST
For a more recent article: https://code.msdn.microsoft.com/AngularJS-with-Web-API-22f62a6e

HTML5 asynchronous file upload, uploaded stream is always invalid

I'm trying to debug an asynchronous file uploader that I built some time ago which is no longer working, I've spent already a good deal of time without success.
The stream that the server is receiving is always corrupted in fact the file (image) that I save cannot be opened.
To simplify debugging I have setup a brand new ASP.NET project, with two main files, the HTML file with the form field and the ASP.NET handler.
Despite the code here being very trivial, I'm still out of luck! :(
Any help is highly appreciated, many thanks!
<!DOCTYPE html>
<html>
<head>
<title>Upload Files using XMLHttpRequest - Minimal</title>
<script type="text/javascript">
function uploadFile() {
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "Handler1.ashx");
xhr.send(fd);
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText);
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
alert("The upload has been canceled by the user or the browser dropped the connection.");
}
</script>
</head>
<body>
<form id="form1" enctype="multipart/form-data" method="post" action="Handler1.ashx">
<input type="file" name="fileToUpload" id="fileToUpload"/>
<input type="button" onclick="uploadFile()" value="Upload" />
</form>
</body>
</html>
and here is the ashx handler:
using System;
using System.Collections.Generic;
using System.Web.Extensions;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
namespace MultipleFileUploadTest
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var stream = context.Request.InputStream;
MemoryStream memoryStream;
ReadFully(stream, out memoryStream);
Byte[] ba = memoryStream.ToArray();
var path = #"C:\Users\giuseppe.JHP\Desktop\Image upload test\uploaded.gif";
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
fs.Write(ba, 0, ba.Length);
}
//DEBUGGING CODE
//I'm opening the same file that was originally picked by the input form field and I'm now comparing the original file with the one received within the context stream. They always differ!
Byte[] ba2 = File.ReadAllBytes(#"C:\Users\giuseppe.JHP\Desktop\Image upload test\a.gif");
//equal evaluates always to false
bool equal = ba.Length == ba2.Length;
if (equal)
{
for (var i = 0; i < ba2.Length; i++)
{
if (ba[i] != ba2[i])
{
equal = false;
i = ba2.Length;
}
}
}
//equal is always false
//if (!equal)
//{
// throw Exception("Stream is not valid");
//}
//The code below will throw a Parameter is invalid exception
//System.Drawing.Image mediaObject = System.Drawing.Image.FromStream(memoryStream);
memoryStream.Close();
}
public static void ReadFully(Stream input, out MemoryStream ms)
{
ms = new MemoryStream();
byte[] buffer = new byte[16 * 1024];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
In case it helped someone else, I've got the code to work, here is what it is changed:
public void ProcessRequest(HttpContext context)
{
if (context.Request.Files != null && context.Request.Files.Count > 0)
{
var file = context.Request.Files[0];
file.SaveAs(#"C:\Users\giuseppe.JHP\Desktop\Image upload test\uploaded.gif");
}
}

Trying to upload a file using ajax in ASP.NET MVC

I am using ASP.NET MVC 3, I want to upload a image file using an ajax form
My Index view code is:
<% using (Ajax.BeginForm("Save","Home", new AjaxOptions() { HttpMethod = "POST", InsertionMode = InsertionMode.Replace }, new { enctype = "multipart/form-data" }))
{%>
<input type="file" /><input type ="submit" value="Submit File"/>
<% } %>
and Controller code is:
[HttpPost]
public ActionResult Save()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View("Index");
}
When I upload a file and click on the button, the ajax form is submitted, but i am getting a Request.File.Count of 0.
Default unobtrusive ajax in mvc doesn't support uploading files. You need to use hidden iframe/plugin (flash, silverlight..)/html5 or combination of those.
Some scripts that might help you:
http://valums.com/ajax-upload/
http://www.uploadify.com/
You can use the the plugins suggested by #Lukáš Novotný or else you can do the following
Create an Generic HTTP handler uploadfile.ashx
Post the data to the file(set the form action="yourpath/UploadFile.ashx"
In the handler you can read the file as
HttpPostedFile uploadedfile = context.Request.Files[0];
Here's my Action that manages the file uploads. Would work with most Ajaxy file uploaders. (I think)
public ActionResult Upload(HttpPostedFileBase uploadfile)
{
try
{
var dr405 = new DR405Service().GetDR405ById(new DR405DBContext(), DR405Profile.CurrentUser.TangiblePropertyId);
var saveLocation = Path.Combine(DR405Service.SavePath + DR405Profile.CurrentUser.TangiblePropertyId);
System.IO.Directory.CreateDirectory(saveLocation);
if ((int)uploadfile.ContentLength / 1024 <= 15000)
{
uploadfile.SaveAs(Path.Combine(saveLocation, Path.GetFileName(uploadfile.FileName)));
var file = new dr405files { TangiblePropertyId = DR405Profile.CurrentUser.TangiblePropertyId, FileName = uploadfile.FileName, UploadDate = DateTime.Now };
//dr405.dr405files.Add(file);
//c.dr405s.Add(dr405);
db.Entry(file).State = file.FileId == 0 ? EntityState.Added : EntityState.Modified;
//db.Entry(dr405).State = EntityState.Modified;
new DR405Service().Save(db);
ViewData["UploadStatus"] = String.Format("File name: {0}, {1}Kb Uploaded Successfully.", uploadfile.FileName, (int)uploadfile.ContentLength / 1024);
}
else
{
ViewData["UploadStatus"] = String.Format("File exceeds 15MB upload limit. Please reduce size and try again.", uploadfile.FileName);
}
}
catch (Exception ex)
{
ViewData.ModelState.AddModelError("_FORM", ex.ToString());
}
return View();
}

Categories