1、编程工具:myeclipse
2、语言:java、struts2框架、JQuery、HTML
一、html页面
在HTML或jsp页面添加如下代码,此代码明确了要上传的文件名和文件:
<form id="form" action="upload/upload" target="_blank" method="post" enctype="multipart/form-data">
<table>
<tr>
<td><input id="fileinput" type="file" name="file"/><input id="filename" name="filename"/></td>
</tr>
</table>
<br/>
<table>
<tr>
<td><input value="上传" id="save" type="submit" /></td>
</tr>
</table>
</form>
二、配置struts.xml文件,我把负责处理上传文件的UploadAction放在了一个叫做action的包里,如果要修改路径请注意修改struts.xml里的配置路径
<package name="upload" namespace="/upload" extends="default"> <!-- 文件处理 -->
<action name="upload" class="action.UploadAction" method="upload">
<result name="success">/upload_result.jsp</result>
</action>
</package>
三、编写UploadAction的接收上传文件的程序,在这里我让action只负责接收,然后再写一个service类负责处理或存储:
package action;
import java.io.File;
import service.UploadService;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport{
private File file;
UploadService uSer = new UploadService();
private String filename ;
private String imgLink;
public String upload(){
this.setImgLink(this.uSer.saveToUrl(file,filename));
return SUCCESS;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public UploadService getuSer() {
return uSer;
}
public void setuSer(UploadService uSer) {
this.uSer = uSer;
}
public String getFilename() {
return filename.replace("*.","123.");
}
public void setFilename(String filename) {
this.filename = filename.replace("*.","123.");
}
public String getSavePath() {
return imgLink;
}
public void setImgLink(String imgLink) {
this.imgLink = imgLink;
}
public String getImgLink() {
return imgLink;
}
}
以下是service类,辅助存储文件或读取文件信息:
package service;
import java.io.File;
import org.apache.commons.io.FileUtils;
import DAO.UploadDAO;
public class UploadService {
UploadDAO udao = new UploadDAO();
public String saveToUrl(File file,String filename){
String savePath = "d:/WaterReportFile/upload";
udao.xlsxWork(file);//我自己的程序是创建了一个DAO类用来读取文件并直接上传至数据库,如果只是单纯为了把上传的文件存储到制定位置请越过这一步。
return this.privateSaveToUrl(file, filename, savePath);
}
public String privateSaveToUrl(File file,String filename,String savePath){
File newfile = new File(savePath);
//判断是否存在存放文件目录,不存在则创建
if(!newfile.exists()){
newfile.mkdirs();
}
//保存文件
try {
//创建一个输出流
File targetFile = new File(savePath,filename); //通过指定路径和源文件文件名创建新文件
FileUtils.copyFile(file, targetFile); //将上传文件拷贝到新文件
}catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("上传文件失败");
}
return (savePath+filename);
}
}