文件上传代码的实现和前台页面
有问题加我QQ 695438455
//运用了java的重载,你可以根据不同的参数进行文件上传
public String saveFile(File srcFile, String uploadFileFileName,
String dirName, boolean inProjectDir, int i) {
return saveFile(srcFile, uploadFileFileName, dirName, String
.valueOf(new Date().getTime()), inProjectDir, i);
}
public String saveFile(File srcFile, String uploadFileFileName,
String dirName, boolean inProjectDir) {
return saveFile(srcFile, uploadFileFileName, dirName, String
.valueOf(new Date().getTime()), inProjectDir, 0);
}
public String saveFile(File srcFile, String uploadFileFileName,
String dirName, String dstFileMainName, boolean inProjectDir) {
return saveFile(srcFile, uploadFileFileName, dirName, String
.valueOf(new Date().getTime()), inProjectDir, 0);
}
/*
* 文件名后缀加
*/
public String saveFile(File srcFile, String uploadFileFileName,
String dirName, String dstFileMainName, boolean inProjectDir, int i) {
String dirPath = ServletActionContext.getServletContext().getRealPath("/");//服务器地址
//System.out.println(dirPath+" dirPath1");
if (!inProjectDir) {
String contextPath = ServletActionContext.getServletContext()
.getContextPath();//获取项目名称路径
// System.out.println(contextPath+" contextPath");
contextPath = contextPath.substring(1, contextPath.length());//截取项目名称
// System.out.println(contextPath+" contextPath1");
dirPath = dirPath.substring(0, dirPath.lastIndexOf(contextPath));//获取服务器的路径
// System.out.println(dirPath+" dirPath2");
}
File dir = new File(dirPath, dirName);
//System.out.println(dirPath+" dirPath "+dirName);
if (!dir.exists()&& !dir.isDirectory()){//判断文件夹是否存在
dir.mkdirs();
}
// String extendName = uploadFileFileName.substring(uploadFileFileName.lastIndexOf("."));//截取图片格式
// System.out.println(extendName+" extendName ");
// String dstFileName = dstFileMainName + extendName;//拼接重命名的图片
String dstFileName = uploadFileFileName;
//System.out.println("dir:"+dir);
this.getSession().setAttribute("dir", dir);
//System.out.println("dstFileName:"+dstFileName+"/n extendName: "+uploadFileFileName);
File dstFile = new File(dir, dstFileName);
//System.out.println("srcFile: "+srcFile+" dstFile: "+dstFile);
copy(srcFile, dstFile);
return dstFileName;
}
前台页面
<form id="jbxxAddForm" method="post" action="${ctx }/json/scftp.action" enctype ="multipart/form-data">
<table cellpadding="0" cellspacing="0" class="dlgtb">
<tr>
<td class="lbl" >选择文件</td>
java中ftp文件上传和中文乱码解决
<td class="lbl" ><input id="pphoto" type="file" name="pphoto" value="选择文件"/></td>
</tr>
</table>
</form>