主要的后台java代码
/***
* 文件拷贝方法
*
* @throws Exception
*/
private void copyFile() throws Exception {
if (file == null) {
return;
}
String[] c = new SimpleDateFormat("yyyy,MM,dd").format(new Date())
.split(",");
StringBuffer sb = new StringBuffer();
for (String temp : c) {
sb.append(temp + "/");
}
PubUser user = (PubUser) ActionContext.getContext().getSession()
.get("SystemUserToken"); // 获取登陆用户
File dir = new File(this.imgFileStore.getRootFile().getPath()
+ "/photo/" + addressList.getUserid());
// 上传的路径在 project.properties 里面改
System.out.println("dir" + dir);
if (!dir.exists()) {
dir.mkdirs();
}
String newfilename = new Date().getTime()
+ fileFileName.substring(fileFileName.lastIndexOf("."));// 获取时间戳
// 生成随机文件名
File new_File = new File(dir, newfilename);
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(new_File);
byte[] b = new byte[512]; // 修改文件名
int a = 0;
while ((a = fis.read(b)) != -1) {
fos.write(b, 0, a);
}
fis.close();
fos.close();
addressList.setPhoto(newfilename); //newfilename生成的文件名字,下面是拼路径
addressList.setPhotourl("photo/" + addressList.getUserid() + "/"
+ newfilename);
}
前台jsp代码
function file_name() {
$('#filename').val($('#file_photo').val());
}
function choice() {
$('#file_photo').click();
$('#zy')
.html(
"<input type='file' name='file' id='file_photo' onblur='yhcf2(this)' class='input_bg' style='width:180px;' onchange='file_name()'/><input name='filename' type='hidden' id='filename' onblur='yhcf2(this)'/>");
}
//上面是js 下面是页面代码
<input type="file" name="file"
id="file_photo" class="input_bg" style="width:180px;"
onchange="file_name()" onblur="yhcf2(this)" /> <input
name="filename" type="hidden" id="filename"
onblur="yhcf2(this)" />