I have a problem to upload a file with my Struts 2 app.
I have this:
<div >
<label for="file">my file</label>
<input type="file" name="releveFile" id="file">
</div>
with this function:
const fileUpload= $('#file')[0].files[0];
const formData = new FormData();
formData.append('fileUpload', fileUpload);
$.ajax({
url: '${pageContext.request.contextPath}/projet.releves.upload.action',
type: "POST",
enctype: 'multipart/form-data',
data : formData,
cache: false,
processData: false,
contentType: false,
success: function (data) {
tata.success('', 'Releve créé avec succès');
$('#releveModal').modal('hide');
this.loadReleves();
},
error: function (err) {
tata.error(err);
}
});
my Struts action is:
@Action(value = "projet.releves.upload", results = {
@Result(name = "success", type = "json", params = {"root", "dto"})
}, interceptorRefs = @InterceptorRef(value = "fileUpload", params = {"maximumSize","100000000"}))
public String upload() {
System.out.println("file =" fileUpload);
System.out.println("file =" uploadFileName);
return SUCCESS;
}
When I click on upload, I get a 200 and I see my file data in the request. However, the
System.out.println("file =" fileUpload);
is always file = null
.
Could you help me to fix this?
CodePudding user response:
The file field is populated by the fileUpload
interceptor. More about these and how it works in Struts 2 see File Upload.
The
fileUpload
interceptor will use setter injection to insert the uploaded file and related data into yourAction
class. For a form field namedupload
you would provide the three setter methods shown in the following example:Example Action class:
package com.example; import java.io.File; import com.opensymphony.xwork2.ActionSupport; public class UploadAction extends ActionSupport { private File file; private String contentType; private String filename; public void setUpload(File file) { this.file = file; }
public void setUploadContentType(String contentType) { this.contentType = contentType; }
public void setUploadFileName(String filename) { this.filename = filename; } public String execute() { //... return SUCCESS; }
}
CodePudding user response:
Hiii, can you please try with below piece of code...
//ajax sample data post
var myform = document.getElementById("formId");
var fd = new FormData(myform);
console.log("Processing... Please wait...");
$.ajax({
url: "upload",
type: "POST",
data : fd,
async:true,
cache: false,
dataType: "json",
processData: false,
contentType: false,
success: function(json) {
if(json.error)
console.log("Error");
else
{
console.log("Upload Successful");
}
},
error: function(err) {
console.log("Exception Occured.");
}
});
//java sample code
private File releveFile;
private String releveFileFileName;
public String upload() {
System.out.println("file =" releveFile);
System.out.println("file name =" releveFileFileName);
return SUCCESS;
}