//前端页面
<form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post" >
<span style="white-space:pre"> </span>上传文件:<input type="file" name="image"><br/>
<span style="white-space:pre"> </span><input type="submit" value="提交"/>
</form>
// strust2 配置
<action name="upload" class="com.itheima.upload.UploadFile" method="upload">
<interceptor-ref name="fileUpload"/>
<interceptor-ref name="basicStack"/>
<result name="success">good_result.jsp</result>
</action>
//java代码
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import com.opensymphony.xwork2.ActionSupport;
public class UploadFile extends ActionSupport{
private static final long serialVersionUID = 1L;
private File image; //上传的文件
private String imageFileName; //文件名称
private String imageContentType; //文件类型
public File getImage() {
return image;
}
public void setImage(File image) {
this.image = image;
}
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
public String getImageContentType() {
return imageContentType;
}
public void setImageContentType(String imageContentType) {
this.imageContentType = imageContentType;
}
public String upload(){
String realpath="F:\\Leanning";
if(image != null){
File savefile = new File(new File(realpath), imageFileName);
System.out.println(savefile);
System.out.println(savefile.getParentFile());
savefile.getParentFile().mkdirs();
if(savefile.getParentFile().exists()){
try {
FileUtils.copyFile(image, savefile);
System.out.println("文件上传成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 若要存入数据库
* fileName是在entity实体类中声明存放文件名称的变量
* yu.setFileName(imageFileName) 这样将文件名称存入数据库
* 文件路径为:savefile
*/
return null;
}
}