Struts2文件上传FileNotFoundException问题

1.使用Struts2实现单个文件上传

注意:要实现文件上传文件,一定要添加两个jar包,commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar
(1)新建fileUpload.jsp
 
    
    	
    	
    	
    
  
(2)新建FileUploadAction.class
package com.tyf.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport{
	private File uploadFile;//用来封装上传的文件
	private String uploadFileContentType;//用来封装上传文件的类型
	private String uploadFileFileName;//用来封装上传文件的文件名
	public File getUploadFile() {
		return uploadFile;
	}
	public void setUploadFile(File uploadFile) {
		this.uploadFile = uploadFile;
	}
	public String getUploadFileContentType() {
		return uploadFileContentType;
	}
	public void setUploadFileContentType(String uploadFileContentType) {
		this.uploadFileContentType = uploadFileContentType;
	}
	public String getUploadFileFileName() {
		return uploadFileFileName;
	}
	public void setUploadFileFileName(String uploadFileFileName) {
		this.uploadFileFileName = uploadFileFileName;
	}
	public String execute() throws Exception{
		InputStream is=new FileInputStream(uploadFile);
		String uploadPath=ServletActionContext.getServletContext().getRealPath("/upload");
		File toFile =new File(uploadPath,this.getUploadFileFileName());
		OutputStream os=new FileOutputStream(toFile);
		byte[] buffer=new byte[1024];//设置缓存
		int length=0;
		while((length=is.read(buffer))>0){
			os.write(buffer,0,length);
		}
		is.close();
		os.close();
		return SUCCESS;
	}
}
(3)fileUploadResult.jsp
  
    上传文件名: ${uploadFileFileName}
文件类型: ${uploadFileContentType}
(4) struts.xml

	
		/fileUploadResult.jsp
		/fileUpload.jsp
	

项目运行
Struts2文件上传FileNotFoundException问题_第1张图片

这里会出现这种问题,后来发现这个目录下没有upload文件夹,新建upload文件夹之后,项目正常运行。
Struts2文件上传FileNotFoundException问题_第2张图片

你可能感兴趣的:(Java框架)