將文件存入webContent目錄下

因爲工做須要要使文件可直接下載,因此準備將文件存入webContent目錄下,以方便訪問。java

弄了很長的一段時間,終於好了,就記錄下來了,以避免之後遇到一樣的問題。web

須要注意的是用這種方法時,若是將項目從服務器上卸下來,webContent裏面保存的信息也就丟失了,若是須要長期保存的話可能不太合適。apache

SERVERPATH 是客戶端訪問服務端的地址服務器

要獲取文件,那麼只需輸入this

SERVERPATH+fileName+ fName就能夠了,其中fileName是文件所在的文件夾名,fName是文件名 code

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class FileAction extends ActionSupport {
	private static String SERVERPATH = "http://xx.xx.xx.xx:8080/xxxx/";
	private static String FILETYPE = "apk";// 文件類型
	private Integer versionFirst;// 版本號參數
	private Integer versionSecond;// 版本號參數
	private Integer versionThird;// 版本號參數
	private File file;//文件

	public String add() {
		String versionNo = versionFirst + "."+ versionSecond + "."+versionThird;
		// 新建的文件夾名
		ActionContext actionContext = ActionContext.getContext();
                //獲取request
		HttpServletRequest request = (HttpServletRequest) actionContext
				.get(ServletActionContext.HTTP_REQUEST);
                //獲取項目在服務器上的真實目錄
		String fileName = request.getSession().getServletContext()
				.getRealPath("")
				+ "\\" + versionNo;
		// 建立一個以版本號命名的文件夾
		File newFile = new File(fileName);
		newFile.mkdirs();
		// 提交完整升級文件到服務器上,並同時重命名
		if (file != null) {
			InputStream is;
			OutputStream os;
			try {
				String fName = fileName + "\\" + versionNo + "." + FILETYPE;
				is = new java.io.FileInputStream(file);
				os = new java.io.FileOutputStream(fName);
				byte buffer[] = new byte[8192];
				int count = 0;
				while ((count = is.read(buffer)) > 0) {
					os.write(buffer, 0, count);
				}
				os.close();
				is.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			return "ERROR";
		}
		return "SUCCESS";
	}


	public Integer getVersionFirst() {
		return versionFirst;
	}


	public void setVersionFirst(Integer versionFirst) {
		this.versionFirst = versionFirst;
	}


	public Integer getVersionSecond() {
		return versionSecond;
	}


	public void setVersionSecond(Integer versionSecond) {
		this.versionSecond = versionSecond;
	}


	public Integer getVersionThird() {
		return versionThird;
	}


	public void setVersionThird(Integer versionThird) {
		this.versionThird = versionThird;
	}


	public File getFile() {
		return file;
	}


	public void setFile(File file) {
		this.file = file;
	}
}
相關文章
相關標籤/搜索