基于struts实现文件的上传
首先是前端的jsp页面
<form>
<input type="file" id="upload" name="upload"/>
<input type="button" value="上传" onclick="up()"/>`
</form>
然后是js
<script src="<%=basePath%>core/scripts/boot.js" type="text/javascript"></script>
<script src="<%=basePath%>core/scripts/EditForm.js" type="text/javascript"></script>
<script src="<%=basePath%>core/scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
funtcion up(){
$.ajaxFileUpload({
url:'xxxxx.action',//用于文件上传的请求地址
fileElementId :'upload',//文件上传空间的id属性,通过这个id,相当于非异步中的myFile
dataType:'text',
success: function(data){
alert(data);
},
error: function(data){
alert(上传文件失败);
}
});
}
};
</script>
然后就是action区域的代码了
//初始化全局变量
private static YbwxSysNewsAttachDTO YbwxSysNewsAttachDtO =new YbwxSysNewsAttachDTO();;
//跟表单提交的input type = file 的name 保持一致
private File upload;
//文件名称 (upload+uploadName)固定格式
private String uploadName;
//文件类型 upload+"ContentType"固定格式
private String uploadContentType;
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadeName() {
return uploadName;
}
public void setUploadName(String uploadName) {
this.uploadName = uploadName;
}
public String getUloadContentType() {
return muploadContentType;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String uploadFile()throws Exception{
//附件上传
String isattachSaveFilePath = request.getRealPath("/");
if (null != upload) {
try {
//String id = UuidUtil.get32UUID();
// 扩展名格式:
String extName = "";
String headName = "";
if (uploadFileName.lastIndexOf(".") >= 0) {
extName = uploadFileName.substring(uploadFileName.lastIndexOf("."));
//获得文件名
headName = uploadFileName.substring(0,uploadFileName.lastIndexOf("."));
}
String name=Tools.RandomFileName()+extName;//文件名
String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String filePath = "/"+dateStr.substring(0,4)+"/"+dateStr.substring(5,7)+"/"+dateStr.substring(8,10)+"/";
String DesPath = isattachSaveFilePath+"/"+"upload/fujian"+filePath;
this.copyFile(new FileInputStream(upload), DesPath,name).replaceAll("-", "");
YbwxSysNewsAttachDtO.setFilename(headName+extName);
YbwxSysNewsAttachDtO.setUrl(filePath+name);
responseWriteHtml("yes");
} catch (Exception e) {
e.printStackTrace();
}
}else{
responseWriteHtml("no");
}
return null;
}
/**
* 写文件到当前目录的upload目录中
*
* @param in
* @param fileName
* @throws IOException
*/
private String copyFile(InputStream in, String dir, String realName)throws IOException {
File file = new File(dir, realName);
if (!file.exists()) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
FileUtils.copyInputStreamToFile(in, file);
return realName;
}
然后执行保存就行了