Upload file excel with struts 2 and ajax [duplicate] - ajax

This question already has an answer here:
Why input type=file not working with $.ajax?
(1 answer)
Closed 4 years ago.
I want upload file excel using ajax in struts 2 but getting null,
I use pure html tag in my jsp page, I think it`s not be a problem
this is what i try to :
jsp :
<form id="uploadImgForm" action="fileUploadAction" method="post" enctype="multipart/form-data">
<input type="file" name="myFile" id="UploadFile">
<input type="button" value="Upload" onclick="uplod()">
</form>
this is ajax function
ajax :
function uplod(){
var form = $('#uploadImgForm')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "fileUploadAction",
data : data,
cache: false,
processData: false,
contentType: false,
success: function() {
console.log("SUCCESS ");
},
error: function() {
console.log("ERROR");
}
});
}
struts 2 xml :
<action name="fileUploadAction" class="id.co.yutaka.mandoc.action.tesUplod">
<result type="json"></result>
</action>
in class action :
public class tesUplod extends ActionSupport{
private File myFile;
String myFileFileName;
#Override
public String execute(){
System.out.println("file ="+ myFile);
System.out.println("file ="+ myFileFileName );
return SUCCESS;
}
public File getMyFile() {
return myFile;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
public String getMyFileFileName() {
return myFileFileName;
}
public void setMyFileFileName(String myFileFileName) {
this.myFileFileName = myFileFileName;
}
}
Output :
myFile =null
myFileFileName =null

I solved this.
what i change is I use a normal action seting in xml
<action name="fileUploadAction" class="id.co.yutaka.mandoc.action.tesUplod">
<interceptor-ref name="loginStack"></interceptor-ref>
<interceptor-ref name="fileUpload">
<param name="maximumSize">100000000</param>
</interceptor-ref>
<result name="success"></result>
</action>
not use json xml action,
I use this and I got a file and any other form value.
may this usefull for other

Related

File upload from Angular - Set file content to Dto

I added a IOperationFilter to swagger so that I can test file uploads for my apis from swagger ui. My Dto is like;
public class ResourceCreateDto : EntityDto
{
public string Title { get; set; }
public string Description { get; set; }
public IFormFile File { get; set; } //file content here
public string ExtendedData { get; set; }
}
Asp.net Core API is:
public async Task<ResourceDto> Create([FromForm] ResourceCreateDto input)
This way I can upload file & other data at the same time (Some have suggested to save file 1st and then save data in another call).
What I am not sure is how to use it in Angular end with Abp. Even though proxies are generated how can I get the angular client to use [File] property and post it's data with the rest to server api?
create DTO:
export class ResourceCreateDto{
title : String;
description: String;
extendedData : String;
file: File;
}
in html
<input class="form-control" type="text" [(ngModel)]="resourceCreateDto.title"/>
<input class="form-control" type="text" [(ngModel)]="resourceCreateDto.description"/>
<input class="form-control" type="file" [(ngModel)]="resourceCreateDto.extendedData"/>
<input class="form-control" type="text" [(ngModel)]="resourceCreateDto.file" (change)="onChangeFile($event)"/>
<button class="btn btn-primary" type="button" (click)="submit()"> Add new </button>
in component
resourceCreateDto: ResourceCreateDto;
file: any;
ngOnInit(): void {
//..
resourceCreateDto = new ResourceCreateDto();
}
onChangeFile(event){
this.file = event.srcElement.files;
}
submit(){
let formData: FormData = new FormData();
formData.append('title', this.resourceCreateDto.title + '');
formData.append('description', this.resourceCreateDto.description + '');
formData.append('extendedData', this.resourceCreateDto.extendedData + '');
formData.append('file', this.file[0], this.file[0].name);
// use service call api
// declare your httpClient
this.httpClient.post<httpResponse>(`${this.BASEURL}/...`, formData,
this.getHttpFileOptions(your token))
.subscribe(response =>{
console.log(response);
},
error=>{
console.log(error);
})
}
setting option http
getHttpFileOptions(token: String): object{
return {
observe: 'response',
responseType: 'json',
headers: new HttpHeaders({
"Accept": "application/json",
'Authorization': 'Bearer ' + token
})
};
}
action in server
[HttpPost("Create")]
public IActionResult Create([FromForm]ResourceCreateDto model, IFormFile File)
Hope to help you!

How to receive a FormData that uploaded by ajax in ActionSupport file in Struts2?

I'm trying to send and receive a file using ajax and Struts2. Here is my code:
JSP
<span class="input-group-btn">
<span class="btn btn-primary btn-file"> Browse
<input id="file" type="file" accept="application/x-pkcs12">
</span>
JS
var file = $('#filepath')[0].files[0];
var formData = new FormData();
formData.append('file', file);
formData.append('filepassword', filepassword);
$.ajax({
url : 'FileAction',
type : 'POST',
async : true,
data : formData,
cache : false,
contentType : false,
processData : false,
success : function(data) {
if (data.jsonResponse.status== 'OK') {
message("Send file successfull.");
}
});
}
struts.xml
<action name = "FileAction" class="package.FileActionSupport"
method = "ReceiveFile">
<interceptor-ref name="basicStack" />
<interceptor-ref name="fileUpload">
<param name="allowedTypes">p12</param>
</interceptor-ref>
<result type="json">
<param name="noCache">true</param>
<param name="excludeNullProperties">true</param>
<param name="excludeProperties"></param>
</result>
</action>
But, In Action Support file, I don't know how to receive a variable with type FormData. I found an JSP/Servlet example receive FormData:
List<FileItem> multiparts = new ServletFileUpload(
(FileItemFactory) new DiskFileItemFactory())
.parseRequest(request); // HttpServletRequest
byte[] ks = null;
for (FileItem item : multiparts) {
if (!item.isFormField()) {
if (item.getContentType().startsWith("application/x-pkcs12")) {
ks = item.get();
}
}
}
So, I tried to get HttpServletRequest in action support file with
HttpServletRequest request = ServletActionContext.getRequest();
and tried again with above code but it doesn't work.
Thank for your help.
UPDATE
var file = $('#filepath')[0].files[0];
var formData = new FormData();
formData.append('file', file); (1)
formData.append('filepassword', filepassword);
Follow this guide,I used MultiPartRequestWrapper and I could get FormData in Action File. But there is a problem. My file have a password and I need it in action file too (filepassword) . But I just get content of file and file name (file)

How to use list inside success function of ajax returned by struts

I have made an ajax call which is mapped to the action class of struts. This action class returns a list. How should I retrieve this list and use it inside success function, i.e., how should i configure struts.xml file so that it returns list and then how to use it my js function?
Struts.xml file:
<action name="getInfo" class="package1.MyClass">
</action>
Action Class:
public String doExecute() throws Exception {
try{
this.list = loadInfo(id);
return SUCCESS;
}catch(Exception e) {
//logger
}
return NONE;
}
Ajax Call:
$.ajax({
type : "GET",
url : url,
success : function(data) {
alert(data);
}
});

how to return json result in jquery function from action class

My aim is to display customer info by costumer id by calling my strus2 action change of selectbox value.
My problem is: what should i return from my action class to get the value in json format
I tried the following code, but i don't know what is wrong with it
<script type="text/javascript">
$(function()
{ alert("This function is calling, on change event of selectbox and customer id="+$(this).val());
$("#customersjsonlstid").change(function(e)
{
$.ajax({
url: 'showCustomerInfoById.action', //action name
data: "customerid=" + $(this).val(),
dataType: "json",
success: function(data) {
// Set the inputs from the json object , json output : {"price": "123.40", "distributor": "XYZ Inc."}
$('#autocompleter_div_result1').val(data.distributor); //showing data on particular div
$('#autocompleter_div_result2').val(data.price); //showing data on particular div
}
});
});
});
</script>
Selectbox:
<sj:select
id="customersjsonlstid"
name="editionType"
href="%{customerJsonselecturl}"
list="lstcust"
listValue="name"
listKey="id"
autocomplete="false"
/>
<div id="autocompleter_div_result">`
struts.xml
<action name="showCustomerInfoById" class="v.esoft.actions.customerdetails.CustomerSelectAction" method="CustomerdetailsById">
<result name="success" type="json"/>
</action>
Action class
public class CustomerSelectAction extends ActionSupport {
private String customerid;
//---------------------------------------------------------
public String CustomerdetailsById()
{
System.out.print("--------Method called, customer id-----------"+customerid);
return customerid;
}
//---------------------------------------------------------
public String getCustomerid() {
return customerid;
}
public void setCustomerid(String customerid) {
this.customerid = customerid;
}
}
Try this:
<action name="showCustomerInfoById"
class="v.esoft.actions.customerdetails.CustomerSelectAction">
<result name="success" type="json"/>
</action>
Hint: removed attribute: method = "CustomerdetailsById"
#Override
public String execute() {
return SUCCESS;
}
In this case, you will get a json object like this:
{
"customerId":"value(customerId)"
}
You can also call showCustomerInfoById.action in your browser, you should see the json shows in the browser.
I faced the same issue and finally it got resolved.
you can try like this :
$("#customersjsonlstid").change(function(e)
{
var customeridJson = $('#customersjsonlstid').val();
$.ajax({
url: 'showCustomerInfoById', //action name same name in struts.xml
data: "customerid=" + customeridJson,
dataType: "json",
async: true,
success: function(data) {
// Set the inputs from the json object , json output : {"price": "123.40", "distributor": "XYZ Inc."}
$('#autocompleter_div_result1').val(data.distributor); //showing data on particular div
$('#autocompleter_div_result2').val(data.price); //showing data on particular div
}
});
});
});
I did the same and it worked for me.
I hope this works for you as well.

How to upload a file without reloading the whole page in mvc3?

I have been working with MVC for the past few days.
I have a problem in one of my pages, i.e I have a page where q user enters the required details and uploads a file. I have two buttons named Upload for Uploading File and Create for creating new profile.
My Problem
My problem is I don't want to reload the whole page when user clicks on upload button. I was thinking of using an webmethod for fileupload.
I don't know if what am I doing wrong here
Can any one correct me
This is my Webmethod in my controller named Create
Controller
[WebMethod]
public string FileUpload(HttpPostedFileBase file, BugModel model)
{
BugModel bug = null;
if (file != null && file.ContentLength > 0)
{
string path = "/Content/UploadedFiles/" + Path.GetFileName(file.FileName);
string savedFileName = Path.Combine(System.Web.HttpContext.Current.Server.MapPath ("~" +path));
file.SaveAs(savedFileName);
BugAttachment attachment = new BugAttachment();
attachment.FileName = "~" + path.ToString();
bug.ListFile.Add(attachment);
model = bug;
}
return "FileUploaded";
}
used a script to call the method
Javascript
<script type="text/javascript">
function UploadFile() {
$.ajax({
type:"Post",
url: "LogABug/FileUpload",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("File Uploaded")
},
error: function () {
ErrorMessage("Try Again");
}
});
}
</script>
can any one tell me how can I do this ...if this is the wrong method correct me the right one with the ideas please
You are uploading the file separately. Therefore you will need two actions:
public string Something(BugModel model) for the model.
public string FileUpload(HttpPostedFileBase file) for the file
Now, I would use jQuery Form Plugin for ajax submitting. Here is an example:
<script type="text/javascript">
$(function () {
$("#file-upload-form").submit(function () {
$(this).ajaxSubmit({
target: "#message",
cache: false
});
return false;
});
});
</script>
#using(Html.BeginForm("FileUpload", "LogABug", FormMethod.Post, new { enctype = "multipart/form-data", id = "file-upload-form" })) {
#Html.ValidationSummary(true)
<fieldset>
#Html.EditorFor(model => model.File)
<input type="submit" value="Upload" />
</fieldset>
}
<div id="message">
</div>
What ever you return from your action will be displayed in the div with id message

Resources