I use asp.net web api for backend and a javascript client.
I use the form input to let the user select a file, and then I make an ajax request to the web api with the FormData, something like this:
var form = $('#uploadForm')[0];
var formData = new FormData(form);
$.ajax({
...
type: 'POST',
data: formData,
...
});
On the backend I receive this request, and get the data from the HttpContent object. Something like this:
try
{
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
return StatusCode(HttpStatusCode.UnsupportedMediaType);
}
var result = await _blobRepository.UploadBlobs(Request.Content);
if (result != null && result.Count > 0)
{
return Ok(result);
}
return BadRequest();
}
I need to have unique file names.
How can I rename the file?
It does not matter if it is the client side, or the backend.
Related
I could successfully compile design automation web application with input file, as RVT and Json attached.
But I need to pass only a Json file, as input for workItem. in ForgeDesignAutomation.js, I wrote it as below. But looks like inputfile need to be stringified . Please help me to correct the syntax below.
here 'inputFile' is a Json file, I am not uploading any rvt file, as my addin takes only a json file as input, which is array of strings and return a rfa file as output.
How to stringify 'inputFile', when it is just a .json file ?
function startWorkitem()
{
var inputFileField = document.getElementById('inputFile');
if (inputFileField.files.length === 0) { alert('Please select an input file'); return; }
if ($('#activity').val() === null) { alert('Please select an activity'); return };
var file = inputFileField.files[0];
let activityId = $('#activity').val();
if (activityId == null)
{
alert('Please select an activity'); return
};
if (activityId.toLowerCase() === "myfirst_da4ractivity+dev")
{
startConnection(function () {
var formData = new FormData();
formData.append('inputFile', file);
//file is not uploading-------I think I could not pass the Json file.
//I need to pass connection ID here too.
writeLog('Uploading input file...');
$.ajax({
url: 'api/forge/designautomation/workitems',
dataType: 'json',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (res)
{
writeLog('Workitem started: ' + res.workItemId);
}
});
});
}
}
From your question, you have a client, that submits to your server, which then submits to Forge.
That way, how you submit to api/forge/designautomation/workitems endpoint varies on how it's expecting the data. As you have a .json file, you don't need to stringfy is, it's passed as a file. If you decide to send it as data, then stringfy and adjust to data: { your JSON data here },
Assuming the file came from your client to your server, you can then submit that JSON file to Forge as an input for your Workitem.
I am trying to send data to a database.php file by ajax. My Index file has a form which will collect a 4 digit input then sends to a js function which sends the data to my db file. At the moment the Db file is being called because I get a result in the console but the 4 digit key is not being sent. I expect I have done something wrong with the ajax script.
Any help please
function addCode(key) {
var code = document.forms[0].code;
if (code.value.length < 4) {
code.value = code.value + key;
}
if (code.value.length == 4) {
document.getElementById("message").style.display = "block";
setTimeout(alarm, 1000, code.value);
}
}
function alarm(code) {
$.ajax({
method: "POST",
url: "alarm.php",
data: code,
cache: false,
success: function(responseText) {
console.log(responseText) // show returned text in console
}
})
emptyCode();
}
function emptyCode() {
document.forms[0].code.value = "";
}
The issue is because you're just sending the value by itself with no key. To fix this you could provide data with an object that will be form encoded when the request is sent:
data: { code: code },
Then in your PHP code you can retrieve the posted value by its key:
$code = $_POST['code'];
I am new to Node.js and I have created a method that should asynchronously fetch jsonp data via ajax and display the retrieved content in a graph. This method works fine when the url points to a static js file (in this case productsData.js) containing jsonp data:
function loadChart(destElementId, alertId) {
$.ajax({
url:'http://localhost:3000/products/data/productsData.js',
type: "GET",
data: {prodId: prodId},
jsonp: true,
dataType : 'json',
jsonpCallback: "jsonpCallback"
});
window["jsonpCallback"] = function(data) {
populateData(data, destId);
}
}
As in normal applications, I want to pass real data fetched via an external web service. I have created the following js file (data-client.js) that retrieves data from a specific web service. When calls are browser-based, the data is fetched successfully as a normal json and is displayed accordingly in the browser.
var express = require('express');
var router = express.Router();
var http = require('http');
var yaml_config = require('node-yaml-config');
var config = yaml_config.load(__dirname + '/../config/app-config.yml');
router.get('/data/:id', function (req, res, next) {
var opts = {
host: config.alertService.host,
port: config.alertService.port,
method: 'GET',
path: '/DataService/rest/receiveData/' + req.params.id
}
var reqGet = http.request(opts, function (dataResponse) {
var responseString = '';
dataResponse.on('data', function (data) {
responseString += data;
});
var response = {x:[],y:[],z:[],t:[]};
dataResponse.on('end', function () {
var responseObject = JSON.parse(responseString);
var accs = responseObject.data.listPCS;
for(var i in accs){
response.x.push(accs[i].accX);
response.z.push(accs[i].accY);
response.y.push(accs[i].accZ);
response.t.push(accs[i].timestamp);
}
res.json(response);
});
});
reqGet.end();
reqGet.on('error', function (e) {
console.error(e);
});
});
module.exports = router;
The first step for using live jsonp data is to replace the previous url value with:
url: 'http://localhost:3000/products/data/'+productId,
The second step is to replace in the data-client.js:
res.json(response);
with:
res.jsonp('jsonpCallback('+ JSON.stringify(response) + ');');
Somehow the data is not fetched. When I try to get the data via the browser (i.e. by entering http://localhost:3000/data/ID937) however I get the following result:
"jsonpCallback({\"x\":[1,1,1],\"y\":[2,1,4],\"z\":[0,0,9],\"t\":[1462790772000,1462790772010,1462790772020]});"
Can someone please tell me where the problem may be? I would be very thankful.
It looks like you are using Express.
jsonp() expects to be passed your raw data, not a string containing the complete response. It also expects to read the callback name from the query string, which jQuery will generate for you if you let it.
So the first thing to do is to fix your client side code so it passes the callback name correctly
On the client
$.ajax({
url: 'http://localhost:3000/products/data/' + productId,
dataType: 'jsonp',
}).done(function(data) {
populateData(data, destId);
});
The changes here are:
GET is the default (and, for JSONP, only option) so there is no need to specify the type.
You are passing the data as a URL path part, not a query string. Drop the data property that you aren't using.
The jsonp property is used to override the callback name. That's harmful, don't do that (likewise, don't specify jsonpCallback). jQuery will generate one for you and add it to the query string.
If you are dealing in JSONP then specify that as the data type, not JSON.
Don't create your own global manually. Pass your function to done and let jQuery make it a global (with a generated name to match the callback).
On the server
Just pass the data structure you want to send back to jsonp().
res.jsonp(response);
The callback name will be read from the query string by Express.
I've seen many examples of uploading files asynchronously using AJAX and ASP.NET MVC, and I can't figure out if/how the Javascript FormData object ever gets used in the controller. The examples I see look like
var formData = new FormData();
formData.append("something", e.target.files[0]););
$.ajax({
type: "POST",
url: '#Url.Action("upload","someController")',
data: formData,
[HttpPost]
public async Task<JsonResult> upload ( )
{
try
{
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
but I'm confused about how to formData is ever used in the controller. If it is used, how does it get inside a controller that has a blank parameter list?
My form will have two file input fields and other fields.The user will be sleecting two different types of files and putting in some data. On submit button I want to send both the files along with the accompanying data to the server.
I have come across two Angular File Uploaders
Angular-file-upload (nervgh)
Angular File upload (danial farid)
Both allow multiple files but for each file there is one Http request .But the behaviour I want is 1 Post request that sends two files and some JSON data.
My backend is in NodeJS.
You will want something like this.
$http({
method: 'POST',
url: '/api/fogbugz/bug/create',
data: { request: $scope.request, files: $scope.files },
headers: { 'Content-Type': undefined },
transformRequest: function(data) {
var formData = new FormData();
formData.append("request", angular.toJson(data.request));
for (var i = 0; i < data.files.length; i++) {
formData.append("File" + (i + 1), data.files[i]);
}
formData.append("nFileCount", data.files.length);
return formData;
}
}).success(function(data) {
}).error(function(error, response) {
});
The important part is that you have to set set Content-Type in your header to undefined instead of multipart/form-data because undefined will set the correct boundary for the form data.