在java代码里面好像得不到js传到action类的Flie对象,希望各位高手解答啊,
jsp代码:
<div class="upload_file">
<img id="loading "src="js/AjaxFileUpload/images/loading.gif" style="display:none;">
<input id="file" type="file" size="20" name="fileToUpload" class="input">
<button class="button" id="buttonUpload">上传</button>
</div>
js代码:
var uploadFile = {
btnUpload : $('div#panel_div .file_list .upload_file button.button'),
loadImg : $('#loading'),
loading : function(){
this.loadImg.ajaxStart(function(){
$(this).show();
}).ajaxComplete(function(){
$(this).hide();
});
},
uploadFile : function(){
$.ajaxFileUpload ({
url :'files!uploadFiles.htm',
secureuri :false,
fileElementId :'file',
dataType : 'json',
success : function (data, status){
alert(data.message);
if(typeof(data.error) != 'undefined'){
if(data.error != ''){
alert(data.error);
}else{
alert(data.msg);
}
}
},
error: function (data, status, e){
alert(e);
}
})
},
init : function(){
var self = this;
this.btnUpload.click(function(){
self.loading();
self.uploadFile();
});
}
}
uploadFile.init();
java代码:
@Autowired
private FilesService filesService;
private File file;
private String fileFileName;
private String fileFileContentType;
public String execute(){
return null;
}
public void uploadFiles(){
try {
@SuppressWarnings("deprecation")
String path = getRequest().getRealPath("/files");
System.out.println(path);
File file = new File(path);
// 判断文件夹是否存在,如果不存在则创建文件
if(!file.exists()){
file.mkdir();
}
if (this.file != null) {
File f = this.getFile();
String fileName = java.util.UUID.randomUUID().toString(); // 采用时间+UUID的方式随即命名
String name = fileName+ fileFileName.substring(fileFileName.lastIndexOf(".")); // 保存在硬盘中的文件名
FileInputStream inputStream = new FileInputStream(f);
FileOutputStream outputStream = new FileOutputStream(path+ "\\" + name);
byte[] buf = new byte[1024];
int length = 0;
while ((length = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, length);
}
inputStream.close();
outputStream.flush();
//保存文件信息到数据库
Files files = new Files();
Person author = (Person)getSession().getAttribute(SessionUtils.ISLOGIN);
files.setName(this.getFileFileName().substring(0,this.getFileFileName().indexOf(".")));
files.setAddress(path + "/"+ this.getFileFileName());
files.setAuthor(author);
filesService.uploadFiles(files);
resultSuccess("上传成功!");
}else {
resultSuccess("上传失败!");
}
} catch (Exception e) {
e.printStackTrace();
resultFailed("上传失败!原因:"+e.getMessage());
}
}
------解决方案--------------------
struts.xml配置一下
<interceptor-stack name="fileUploadStack">
<interceptor-ref name="fileUpload" />
<interceptor-ref name="defaultStack" />