File upload to the asp.net web service not working - javascript

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?

Related

Get .wav blob from url

I'm trying to get a blob from an URL (in my case leads to a .wav file).
The URL is located at my own website, so I only do requests to the same site.
The purpose:
A user has uploaded some .wav files to my website to one schema
The user wants to copy one or more .wav files from one to another schema
The user selects the audiofiles to copy without uploading the files again.
The user interface looks like this:
The problem:
Each audiofile is located in its own directory.
https://mywebsite.nl/media/audiofiles/schemaGUID/recording.wav
So when copying to another schema, the file or files needs to get re-uploaded to the directory of the other schema.
The code im using to upload the selected audiofiles is this:
newwavfiles.forEach(function (item) {
var name = item["name"];
var filename = item["filename"];
var fileblob = fetch('http://mywebsite.nl/media/audiofiles/12345677/recording.wav').then(res => res.blob());
var formData = new FormData();
formData.append('file', fileblob, filename);
formData.append('guid', guid);
// upload file to server
$.ajax({
url: 'index.php?action=uploadAudiofile',
type: 'post',
data: formData,
enctype: 'multipart/form-data',
contentType: false,
processData: false,
success: function (response) {
},
error: function (xhr, status, error) {
console.log(xhr);
var errorMessage = xhr.status + ': ' + xhr.statusText
}
});
});
To get the blob of the file I tried this:
var fileblob = fetch('http://mywebsite.nl/media/audiofiles/12345677/recording.wav').then(res => res.blob());
But then I get this error:
Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'.
Does anyone have a solution to get the .wav file blob from an URL?

Copy file from local to the server nodejs

I am using nodeJS and I would like to upload a file to the server.
I have pug page where the user fill all the information and choose a file with filechooser. Then I want to send all the information on the page to the server. Therefore, I am using ajax to send a json object and given that file object can not be send through a json object I convert the File object to a json object like this:
function uploadGenome() {
var file = $(':file')[0].files[0];
var fileObject = {
'lastMod': file.lastModified,
'lastModDate': file.lastModifiedDate,
'name': file.name,
'size': file.size,
'type': file.type
};
return fileObject;
}
Then I add everything in a Json object:
var data = {};
data.file = uploadGenome();
data.name = inputs[0].value;
data.description = inputs[1].value;
data.start = inputs[3].value;
data.end = inputs[4].value;
And finally, I send everything with ajax:
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: url,
success: function (data) {
console.log('success');
console.log(JSON.stringify(data));
if (data === 'done')
{
window.location.href = "/";
} else {
alert('Error Creating the Instance');
}
},
error: function () {
console.log('process error');
}
});
On the server side with NodeJS I get everything, but now how could I copy the file that I get in data.file on the server ? I mean create a copy on the project folder which is on a server.

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

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 .

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";
}
}
}

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.

Categories

Resources