Struts2 the Action upload file get json data

来源:互联网 发布:金十数据日历桌面 编辑:程序博客网 时间:2024/05/22 00:48

Java Code:

package com.shop.action;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.text.SimpleDateFormat;import java.util.Date;import javax.servlet.http.HttpServletRequest;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;import com.shop.uitl.FileUitl;import com.shop.uitl.ServerUrl;public class FileUpload extends ActionSupport {private File file; // 上传的文件private String fileFileName; // 文件名称private String fileContentType; // 文件类型private String path; // 返回路径private boolean status; // 状态private String message; // 提示信息private String url;//返回的url调用路径public String getUrl() {return url;}public void setUrl(String url) {this.url = url;}public void setFile(File file) {this.file = file;}public void setFileFileName(String fileFileName) {this.fileFileName = fileFileName;}public String getFileFileName() {return fileFileName;}public String getFileContentType() {return fileContentType;}public void setFileContentType(String fileContentType) {this.fileContentType = fileContentType;}public String getPath() {return path;}public void setPath(String path) {this.path = path;}public boolean isStatus() {return status;}public void setStatus(boolean status) {this.status = status;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}@Overridepublic String execute() throws Exception {// TODO Auto-generated method stubHttpServletRequest request=ServletActionContext.getRequest();String path = ServerUrl.getServerPath(request, "upload");String save=ServerUrl.getDiskPath(request, "upload");if (file == null) {this.setMessage("文件为空!");status = false;return SUCCESS;}try{//创建目录 按照当天的日期来创建Date date=new Date();SimpleDateFormat format=new SimpleDateFormat("yyyyMMdd");SimpleDateFormat format2=new SimpleDateFormat("yyyyMMddhhmmss");String strDate=format.format(date);//检查文件夹是否存在if(!new File(save+strDate).isDirectory()){new File(save+strDate).mkdir();}//重命名文件String name=FileUitl.getExtensionName(fileFileName);fileFileName=format2.format(date)+name;//写入到磁盘FileInputStream in=new FileInputStream(file);File outFile=new File(save+strDate+"\\"+fileFileName);FileOutputStream out=new FileOutputStream(outFile);//文件损坏int ch=0;while((ch=in.read())!=-1){out.write(ch);}out.flush();out.close();in.close();setMessage("文件上传成功!");//响应信息setPath("upload/"+strDate+"/"+fileFileName);//相对路径setStatus(true);//状态setUrl(ServerUrl.getServerPath(request, "upload/"+strDate+"/"+fileFileName));//绝对路径System.out.println(fileContentType + "已经接受到数据!");return SUCCESS;}catch (Exception e) {setStatus(false);setMessage("上传过程中发送了异常,上传失败!");}return SUCCESS;}}


原创粉丝点击