How to bind javascript array with #RequestParam using FormData? - javascript

The problem is binding javascript arraylist with RequestParam annotation.
I have a form data like this works fine if there is no nokDataList.
nokInfoDatas is an javascript array that in console it looks:
var requestData = JSON.stringify(nokInfoDatas);
console.log("nokInfoDatas");
console.log(nokInfoDatas);
console.log("requestData");
console.log(requestData);
var fd = new FormData();
fd.append('photo', file);
fd.append('testId', testId);
fd.append('nokDataList', nokInfoDatas);
var ajaxData = {
type: "POST",
data: fd,
processData : false,
contentType : false,
url: sendUrl,
headers: headersData,
};
Backend side:
public #ResponseBody String answer(HttpServletRequest request,
#RequestParam(value = "photo") MultipartFile photo,
#RequestParam(value = "testId") String testId,
#RequestParam(value = "nokDataList") List<NokDataDTO> nokInfoDtos
)

You can try as follows :
Create a Blob with your JSON data (requestData) :
var requestData = JSON.stringify(nokInfoDatas);
var fd = new FormData();
fd.append('photo', file);
fd.append('testId', testId);
fd.append('nokDataList', new Blob([requestData], {
type: "application/json"
}));
Change #RequestParam to #RequestPart for parsing JSON with multi-part.
public #ResponseBody String answer(HttpServletRequest request,
#RequestParam(value = "photo") MultipartFile photo,
#RequestParam(value = "testId") String testId,
#RequestPart(value = "nokDataList") List<NokDataDTO> nokInfoDtos
)

Related

application/json content type store location

the result of content type : "application/x-www-form-urlencoded" stored in Request.Form in Asp MVC.
but for "application/json" i cant find the store location
here is the code that i use:
ajax part
// reading form data
var form = $("form")[0];
var formData = new FormData(form);
var object = {};
formData.forEach(function(value, key){
object[key] = value;
});
var data = JSON.stringify(object);
// ajax part
// POST application/json; charset=utf-8
$.ajax({
type: "POST",
url: "#Url.Action("FormSubmit","Home")",
data: data,
dataType: "json",
async: true,
contentType: "application/json",
processData: true,
success: function(result) { },
error: function(result) { }
});
Controller Part
[HttpPost]
public ActionResult FormSubmit(string input1, string input2)
{
var httpContext= HttpContext;
var response = Response;
var request = Request;
throw new NotImplementedException();
}
You can use controller like this:
[HttpPost]
public ActionResult SomeAction(string data)
{
List<YOUR_MODEL_CLASS> payloadObj = Newtonsoft.Json.JsonConvert.DeserializeObject<List<YOUR_MODEL_CLASS>>(data)(modelData);
// process your data
}
Found the answer
i just need to read post Payload
here is the code
[HttpPost]
public ActionResult FormSubmit()
{
Request.InputStream.Position = 0;
var reqMemStream = new MemoryStream(HttpContext.Request.BinaryRead(HttpContext.Request.ContentLength));
string reqString = Encoding.ASCII.GetString(reqMemStream.ToArray());
throw new NotImplementedException();
}

How to pass blob value through ajax call in javascript?

We are Generating blob value and want to get it inserted into the database through SQL Server.
We are able to pass the blob value and through the help of Ajax call we are trying to get it to insert but we are receiving the error Uncaught (in promise) TypeError: Failed to execute 'array buffer on 'Blob': Illegal invocation code. And in WebServices, we are passing it as byte value byte[] BLOB while in SQL we are using var binary(max) to store the value.
async function pdfhandler() {
let pdfBlob = '1';
var mystring = "Hello World!";
pdfBlob = new Blob([mystring]);
updateblobdata(pdfBlob);
console.log(pdfBlob);
}
function updateblobdata(blobvalue) {
debugger;
/// Insert Blob into Database ///
console.log('updateblobdata called');
const urlParams = new URLSearchParams(window.location.search);
const myParamtag = urlParams.get('104');
const mymodelval = urlParams.get('DuganHosp-0002');
var wonumval = '104'; var tagnumval = 'DuganHosp-0002';
var Modeval = 'U';
var BLOBval = blobvalue;
$.ajax({
url: 'TestTool_WebService.asmx/UpdateHtmlBLOBContent',
data: {
WoNum: wonumval,
Tagnum: tagnumval,
BLOB: BLOBval,
Mode: Modeval,
},
method: 'post',
dataType: 'json',
contentType: false,
processData: false,
cache: false,
success: function (data) { },
});
}
You can send files only with content-type: multipart/form-data.
function updateblobdata(blobvalue) {
const formData = new FormData();
formData.append('blob', blobvalue);
$.ajax({
url: 'TestTool_WebService.asmx/UpdateHtmlBLOBContent',
data: formData,
method: 'post',
dataType: 'json',
contentType: 'multipart/form-data',
processData: false,
cache: false,
success: function (data) { },
});
}
No Still its not working.Its not coming to this point for blob value.
[WebMethod]
public void UpdateHtmlBLOBContent(string WoNum, string Tagnum, byte[] BLOB, string Mode)
{
string htmldoc = null;
using (SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["ConStr1"]))
{
SqlCommand cmd = new SqlCommand("TestTool_PrototypeprocBlobRun", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Workorder", WoNum);
cmd.Parameters.AddWithValue("#Equipment", Tagnum);
cmd.Parameters.AddWithValue("#HTML_blob", BLOB);
cmd.Parameters.AddWithValue("#MODE", "U");
con.Open();
int i = cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
htmldoc = "Success";
}
dr.Close();
}
Context.Response.Write(htmldoc);
}
}

jQuery.ajax() : send blob object to Spring REST

How to send by jQuery.ajax() an object containing types String and Blob and receive it on the Spring REST side by #RequestBody myModelClass?
JavaScript:
function savePicture() {
var img = canvas.toDataURL('image/jpeg');
var blob = new Blob([img], {type: 'image/jpeg'});
var d = new Date();
var cd = (d.getUTCMonth()+1) + "/" + d.getUTCDate() + "/" + d.getUTCFullYear();
var fd = new FormData();
fd.append('name', 'mypicture');
fd.append('author', 'Kate');
fd.append('createdDate', cd);
fd.append('content', blob);
$.ajax({
type: "POST",
url: "/send",
data: fd,
processData: false,
contentType: 'application/json',
cache: false,
timeout: 600000,
success: function (data) {
console.log(data);
},
error: function (e) { }
});
}
Spring REST (The function to receive the object from ajax() and save to the database.):
#PostMapping(value="/send")
public ResponseEntity<?> sendPictureToDatabase(#RequestBody Picture picture, Errors errors) throws IOException {
pictureService.savePicture(picture);
AjaxResponseBody result = new AjaxResponseBody();
result.setMsg("success");
result.setResult(pictureService.getAllPictures());
return ResponseEntity.ok(result);
}
My model:
#Entity
public class Picture {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(nullable=false)
private Long id;
#Column(nullable=false)
private String name;
#Column(nullable=false)
private String author;
#Column(name="CREATED_DATE", nullable=true)
#Convert(converter = LocalDateAttributeConverter.class)
private LocalDate createdDate;
#Column(nullable=false)
#Lob
private String[] content;
//...
}

post error Required MultipartFile [ ] parameter not present

Does anyone know why I am getting the above error? I cant see why? please see my code below and advise where i can fix this error. The aim is to upload multiple files to a location. It used to work for a single file, however it looks like the formdata or ajax request is only used to accepting one file and not multiple. I am not doing this in PHP, only javascript/java. Please help.
function makeProgress(number){
var url = getRelativeURL("web/fileUpload");
var formData = new FormData();
formData.append('number', number);
fls = document.getElementById("attachmentFileUploadInput").files; //length of files...
console.log(fls);
for(j=0;j<fls.length;j++){
formData.append('files[]', fls[j]); //note files[] not files
}
//formData.append('file', $('input[type=file]')[0].files[0]);
console.log("form data " + formData);
$.ajax({
url : url,
data : formData,
processData : false,
contentType : false,
type : 'POST',
success : function(data) {
FileUploadVisible(true);
$('#attachmentModal').modal('hide')
$(':input','#attachmentModal').val("");
$("#pbarmain").hide();
$("#pbar").hide();
$("#actionPlanDiv").hide();
setObjectEnabled('#Upload',false);
},
error : function(err) {
FileUploadErrorVisible(true);
}
});
}
#Bean(name = "multipartResolver")
public CommonsMultipartResolver commonsMultipartResolver(){
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
commonsMultipartResolver.setDefaultEncoding("utf-8");
commonsMultipartResolver.setMaxUploadSize(5000000); // 5000000 -> 5MB
return commonsMultipartResolver;
}
}
#RequestMapping(value = { "/fileUpload" }, method = RequestMethod.POST)
#ResponseBody
public String uploadFile( #RequestParam("number") String number, #RequestParam("files") MultipartFile[] files, MultipartHttpServletRequest req, HttpServletResponse res)
{
for (MultipartFile file : files) {
try {
File directory = new File(UPLOADED_FOLDER + number);
if (! directory.exists()){
directory.mkdir();
}
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + number + "//" + file.getOriginalFilename());
Files.write(path, bytes);
logger.info("You have successfully uploaded '" + file.getOriginalFilename() + "'");
return("File Uploaded");
} catch (Exception e) {
res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
logger.error("Failed to upload file '" + file.getOriginalFilename() + "'", e);
return("File Not Uploaded");
}
}
return "redirect:/fileUpload";
}
}
you have to use..
#RequestMapping(method = RequestMethod.POST, headers = ("content-
type=multipart/*"), produces = "application/json", consumes = "file/*")
public String uploadFile(#RequestParam("number") String number, #RequestParam("files") MultipartFile files) {
and also use contentType: 'multipart/form-data into javascript code
url : url,
data : formData,
processData : false,
contentType: 'multipart/form-data',
type : 'POST',
success : function(data) {

Cant get array from ajax

I have asp.net application where need to implement autocomplete, I try to load list of names from server side and then deserealize it in js code, but have an 500 error, can anybody help me?
Unknown web method GetListofCompanies.
Parameter name: methodName
Code:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetListofCompanies(string name) {
var companies = _companyRepo.GetAll().Select(x => x.Name).ToList();
// Create a JSON object to create the response in the format needed.
JavaScriptSerializer oJss = new JavaScriptSerializer();
// Create the JSON response.
String strResponse = oJss.Serialize(companies);
return strResponse;
}
JS:
var name = "";
$.ajax({
url: "Company.aspx/GetListofCompanies",
type: "post",
data: { name: name },
dataType: "json",
contentType: 'application/json',
success: function (data) {
// Get the data.
var responseArray = JSON.parse(data.d);
$("#txtName").autocomplete({
source: responseArray
});
}
});
// Namespaces.
using System.Web.Services;
using System.Web.Script.Serialization;
[WebMethod]
public static string GetListofCompanies(string name)
{
List<string> companies = new List<string>();
companies.Add("Company1");
companies.Add("Company2");
companies.Add("Company3");
companies.Add("Company4");
companies.Add("Company5");
// Create a JSON object to create the response in the format needed.
JavaScriptSerializer oJss = new JavaScriptSerializer();
// Create the JSON response.
String strResponse = oJss.Serialize(companies);
return strResponse;
}
// JS
function request() {
var name = "";
var data = { name: name };
$.ajax({
url: "Default.aspx/GetListofCompanies",
type: "POST",
contentType: 'application/json',
data: JSON.stringify(data)
}).success(function (data) {
// do your stuff here
})
.fail(function (e) {
alert("Error");
});
}

Categories