Trying to POST multipart/form-data by javascript to web api - javascript

Here i have a form in which i have a input type file to upload my file when the upload button is click i need to post the multipart/form-data to web api
where i upload the file to Minio Server.I have pasted the javascript and web api i use below.
When i press upload button after i get 500 (Internal Server Error).Help me with suggestions.
$("#upload").click(function () {
var file = new FormData($('#uploadform')[0]);
file.append('tax_file', $('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: 'http://localhost:53094/api/values',
data: file,
//use contentType, processData for sure.
contentType: "multipart/form-data",
processData: false,
beforeSend: function () {},
success: function (msg) {
$(".modal .ajax_data").html("<pre>" + msg +
"</pre>");
$('#close').hide();
},
error: function () {
$(".modal .ajax_data").html(
"<pre>Sorry! Couldn't process your request.</pre>"
);
$('#done').hide();
}
});
});
[HttpPost]
public string Post(IFormFile file)
{
try
{
var stream = file.OpenReadStream();
var name = file.FileName;
minio.PutObjectAsync("student-maarklist", "sample.jpeg", stream, file.Length);
return "Success";
}
catch (Exception ex)
{
return ex.Message;
}
}

I think you need not mention localhost just the path to the file will do. or replace it with IP of the localhost.

Sorry i have dont a mistake the name i appended in javascript is not save as the name i gave in web api.
I changed,
file.append('tax_file', $('input[type=file]')[0].files[0]);
To
file.append('file', $('input[type=file]')[0].files[0]);
and it worked .

Related

Javascript Callback function after download Excel

I need to send mail to user after downloading .csv file. I am not sure how to set callback function after file gets downloaded.
$.ajax({
url: '#Url.Action("GetAllCustomer", "Customers")',
type: 'POST',
data: { 'customerIds': strCustomerId },
success: function (result) {
if (result == "Success") {
location.href = '#Url.Action("DownloadFile", "Customers", new { extension = "csv"})';
} else {
toastLast = toastr.error("No data found", "Generating File");
}
}
});
In above code in first call i am getting all the customers. On success callback i am calling DownloadFile method to download csv file. i have requirement to send mail after downloading file but i am not sure how will i know that file is downloaded. Or Can I achieve with some other way.
Please find my DownloadFile method of controller as below.
public ActionResult DownloadFile(string extension)
{
var dateTime = DateTime.Now.ToString("M.dd.yy");
var fileName = dateTime + " Application File." + extension;
var array = TempData["Output"] as byte[];
if (array != null)
{
var file = File(array, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
return file;
}
else
{
return new EmptyResult();
}
}
Don't use this line
location.href = '#Url.Action("DownloadFile", "Customers", new { extension = "csv"})';
Instead use a ajax request to the Action method
$.ajax({
type: "POST",
url: '#Url.Action("DownloadFile", "Customers")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(){
//add your sccuess handlings
}
error: function(){
//handle errors
}
});

How to Upload Files using ajax call in asp.net?

I have created a small asp.net web forms application, to manage emails , i have created a little interface contains mandatory information to send a email, like from , to , subject etc. now i want to attach files to the email, i have used asp.net file upload controller to upload files,
and have to attach multiple files,
Now i want to send this details to code behind, so i thought the best way is to use ajax calls , because i don't want to refresh my page, but i can't figure out the way how to send the attached files to the server side,
i have read some articles and they saying i have to use FormData to send the files ,
then i have created a FormData object and appended all the attached files to the object.but how to pass this object to server side,
my js code as below,
function sendEmail() {
var data = new FormData();
var files = $('.attachment');
$.each(files, function (key, value) {
var file = $(value).data('file');
data.append(file.name, file);
});
$.ajax({
url: "OpenJobs.aspx/sendEmail",
type: "POST",
async: false,
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: null,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
}
Any help?
You need to use Generic handler to upload files using ajax, try below code:
function sendEmail() {
var formData = new FormData();
var files = $('.attachment');
$.each(files, function (key, value) {
var file = $(value).data('file');
formData.append(file.name, file);
});
$.ajax({
url: "FileUploadHandler.ashx",
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: formData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
}
Generic handler
<%# WebHandler Language="C#" Class="FileUploadHandler" %>
using System;
using System.Web;
public class FileUploadHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
string fname = context.Server.MapPath("~/uploads/" + file.FileName);
file.SaveAs(fname);
}
context.Response.ContentType = "text/plain";
}
}
}

File upload to the asp.net web service not working

I'm trying to upload file to the web service using JavaScript and JQuery. My current implementation is working correctly in the local environment.
But after deploying my solution to the server and try to access from outside it's not working and saying server side error occurred. Other thing I found is other web methods of the same web service are working correctly and just this file upload method is not working.
Here is my asp.net web service file upload method.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public object SaveFile()
{
var bugID = int.Parse(HttpContext.Current.Request.Form["bugID"]);
var fileName = HttpContext.Current.Request.Form["name"];
var fileType = HttpContext.Current.Request.Form["type"];
var file = HttpContext.Current.Request.Files[0];
// file saving logic
// .....
return new JavaScriptSerializer().Serialize(new
{
Message = 1,
Name = fileName,
DocumentID = attach.DocumentID // Saved file ID
});
}
Here is the javascript method I used to upload the file to the web service
function uploadFile() {
var data = new FormData(),
file = $("#fileToUpload")[0].files[0];
data.append("name", file.name);
data.append("size", file.size);
data.append("type", file.type);
data.append("file", file);
data.append("bugID", bugID);
$.ajax(
{
url: baseURL + "Webservice/BugsWebService.asmx/SaveFile",
dataType: "xml",
type: "POST",
data: data,
cache: false,
contentType: false,
processData: false,
success: function (res) {
console.log(res);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
}
In development environment web service url is
http://localhost:55225/Bugs/View.aspx
When host the site url is
http://[ip-address]/Internal/Bugs/View.aspx
This is the error I'm getting when try to upload the file
http://[ip-address]/Internal/Webservice/BugsWebService.asmx/SaveFile
500 (Internal Server Error)
What is the issue with my implementation?

Upload files to Dropbox using a Dropbox Core API in Javascript

I am working on a simple chrome-extension that needs to upload files to the user's dropbox folder. I am using the simple AJAX requests as mentioned below to upload files, however it works for files with extensions such as .txt, .json, .c, etc i.e. files whose mime type is of type text/plain or similar type but all other file types such as pdfs, image files etc get corrupted and produce blank contents. What am I missing in uploading the files the correct way.
function startUpload()
{
var folderPath = $(this).closest('tr').attr('path')+'/';
var file = $("#upload_file")[0].files[0];
if (!file){
alert ("No file selected to upload.");
return false;
}
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (evt) {
uploadFile(folderPath+file.name,evt.target.result,file.size,file.type);
}
}
//function to upload file to folder
function uploadFile(filepath,data,contentLength,contentType){
var url = "https://api-content.dropbox.com/1/files_put/auto"+filepath;
var headers = {
Authorization: 'Bearer ' + getAccessToken(),
contentLength: contentLength,
};
var args = {
url: url,
headers: headers,
crossDomain: true,
crossOrigin: true,
type: 'PUT',
contentType: contentType,
data : data,
dataType: 'json',
success: function(data)
{
getMetadata(filepath.substring(0,filepath.lastIndexOf('/')),createFolderViews);
},
error: function(jqXHR)
{
console.log(jqXHR);
}
};
$.ajax(args);
}
I believe the issue is reader.readAsTextFile(file, "UTF-8"). If the file isn't a text file, this will misinterpret the contents. I think you want reader.readAsBinaryString or reader.readAsArrayBuffer. (I haven't tested it myself.)
EDIT
After testing this myself, I found that readAsArrayBuffer is what you need, but you also need to add processData: false as an option to $.ajax to prevent jQuery from trying to convert the data to fields in a form submission.
Also be sure to use dataType: 'json' to properly parse the response from the server.

Django + Ajax | File Upload | Server doesn't recognise Ajax Request

I am trying to implement file upload using ajax with Django but facing some problem.
When the user tries to upload the files after selecting the file and submitting the form, then as per my understanding , an ajax request should be send to the server using POST method ,but in my case a POST request is being made to the server, but the server is not able to identify it as an ajax request and browser is redirected to http://<server>:<port>/upload/ and the contents on this page are as follows.
{"status": "error", "result": "Something went wrong.Try Again !!"}
Django Version: 1.6.2
Python Version: 2.7.5
Also, testing on Django Development Server.
views.py
def upload(request):
logging.info('Inside upload view')
response_data = {}
if request.is_ajax():
logging.info('Is_AJAX() returned True')
form = UploaderForm(request.POST, request.FILES)
if form.is_valid():
logging.info('Uploaded Data Validated')
upload = Upload( upload=request.FILES['upload'] )
upload.name = request.FILES['upload'].name
upload.save()
logging.info('Uploaded Data Saved in Database and link is %s' % upload.upload)
response_data['status'] = "success"
response_data['result'] = "Your file has been uploaded !!"
response_data['fileLink'] = "/%s" % upload.upload
return HttpResponse(json.dumps(response_data), content_type="application/json")
response_data['status'] = "error"
response_data['result'] = "Something went wrong.Try Again !!"
return HttpResponse(json.dumps(response_data), content_type='application/json')
Template
<form id="uploadForm" action="/upload/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="fileInput" class="input-file" name="upload" type="file">
<input type="submit" value="Post Images/Files" />
</form>
Javascript 1:
$('#uploadForm').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Javascript 2
var options = {
url: '/upload/',
type: "POST",
error: function(response) {
alert('Something went Wrong. Try Again');
},
success: function(response) {
if ( response.status == 'success' ) {
alert('success');
}
}
};
$('#uploadForm').ajaxSubmit(options);
Question:
1) Why is Django not able to recognize the ajax request and value of request.is_ajax() is always False.
2) Even if the server doesn't recognize ajax request why is my browser getting redirected to another page ?
There is another similar question here but with no result.
This works for me. You need a jquery.form.js
$("#uploadForm").submit(function(event) {
$(this).ajaxSubmit({
url:'{% url upload_file %}',
type: 'post',
success: function(data) {
console.log(data)
},
error: function(jqXHR, exception) {
console.log("An error occurred while uploading your file!");
}
});
return false;
});
Here's the similar question here with answers.
Make sure that javascript code block
$('#uploadForm').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
loaded after your uploadForm html form in DOM on page. In your case seems you trying to bind submit handler with form element which not yet loaded so when you click, it send simple POST request.
1) why is_ajax() not working?
Have you included the JQuery form plugin (jquery.form.js) ? ajaxSubmit() needs that plugin.
Take a look at http://jquery.malsup.com/form/
If it's already done, you might take a look at the HTTPRequest object
Django Documentation says HttpRequest.is_ajax()
Returns True if the request was made via an XMLHttpRequest. And if you are using some javascript libraries to make the ajax request, you dont have to bother about this matter. Still you can verify "HTTP_X_REQUESTED_WITH" header to see if Django received an XMLHttpRequest or not.
2) Why page redirects?
As I said above, JQuery form plugin is needed for handling the ajax request and its call back. Also, for ajaxSubmit() you need to override the $(#uploadForm).submit()
$('#uploadForm').submit( function (){
$(this).ajaxSubmit(options);
return false;
});
Hope this was helpful :)

Categories

Resources