这周主要实现指标项增添时,用户文件的上传。用户可以上传多个文件,上传后的文件名存储在文件表中,表中添加指标项表主键值,实现指标项对文件的一对多绑定。
这里就出现了一些问题:
1.是用户文件上传的问题,指标项增添页面生成时,指标项的主键并未生成(主键是用sequence在插入表中时生成的),这时该如何实现文件与指标项的绑定。
解决方法:现在界面上实现文件上传,文件名存储在文件表中,上传后返回文件表的文件ID到页面隐藏域中。如果用户点击提交,先保存指标项,返回指标项主键,再讲主键和文件id存储在文件表中。
2.用户上传文件后若不保存,文件还是在服务器中,久而久之,服务器有存储负担。
解决方法:先将上传的文件存储在临时位置,若用户保存,则将文件移至指定的存储位置,每隔一段时间删除临时位置的文件。
下面是文件存储实现过程,由于第一次做,花了好几天,回忆下,增强记忆。
过程:
1.在用户界面中增加文件选择控件和上传按钮:
<td width="15%">上传文件:</td>
<td><input id="file" type="file" name="file" /></td>
</tr>
<tr>
<td ><input id="upload" enabled="false" type="button" value="上传"onclick="return uploadFile();"/></td>
2.在js里上添加上传事件:
function uploadFile(){
$.ajaxFileUpload({
url:'<c:url value="/portal/f11010101/uploadFile.action"/>',
secureuri:false,
fileElementId : 'file',
dataType : 'json',
success:function(data,status){
alert("上传成功");
var textbox =mini.get("filename");
textbox.setValue(textbox.getValue()+";"+data.result[0].path);
var hidden = mini.get("fileid");
hidden.setValue(hidden.getValue()+data.result[0].fileid);
alert(hidden.getValue());
},
error:function(data,status,e){
alert(e);
alert(data.msg);
}
});
}
3.编写一个上传文件的抽象父类:
package com.wondersgroup.hzrsmh.portal.f11010101.action;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ParameterAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.wondersgroup.framework.core.exception.BusinessException;
import com.wondersgroup.framework.core.web.struts2.AjaxProvider;
import com.wondersgroup.framework.core5.model.vo.ValueObject;
public abstract class BaseUploadFileAction extends ActionSupport implements AjaxProvider, ModelDriven, SessionAware,
ParameterAware, ServletRequestAware, ServletResponseAware{
private Writer writer;
private String defaultEncoding;
public static final String ERRORS = "{success:false,result:[{}],exception:[{msg:'%s'}]}";
protected Map session;
protected Map parameters;
protected HttpServletRequest servletRequest;
protected HttpServletResponse servletResponse;
private String responseData;
private String errorResultLocation;
private boolean ajaxSuccess;
public BaseUploadFileAction() {
this.defaultEncoding = "UTF-8";
}
@Override
public String execute() throws Exception {
String result = null;
try {
result = operate();
}
catch (Exception e) {
writerJson(String.format(ERRORS, getErrorMsg(e)));
e.printStackTrace();
return null;
}
writerJson(result);
return null;
}
public String getErrorMsg(Throwable throwable) {
if (throwable instanceof BusinessException) {
return throwable.getMessage();
}
return getErrorMsg(throwable.getCause());
}
public void writerJson(String json) throws IOException {
if(json ==null ||json.trim().length()==0)
return;
HttpServletResponse response = ServletActionContext.getResponse();
String contentType = "text/html" + ";charset=" + defaultEncoding;
response.setContentType(contentType);
response.getWriter().write(json);
response.getWriter().flush();
}
public Object getModel() {
return getValueObject();
}
public Map getSession() {
return this.session;
}
public void setSession(Map session) {
this.session = session;
}
public Map getParameters() {
return this.parameters;
}
public void setParameters(Map parameters) {
this.parameters = parameters;
}
public HttpServletRequest getServletRequest() {
return this.servletRequest;
}
public HttpServletResponse getServletResponse() {
return this.servletResponse;
}
public void setServletRequest(HttpServletRequest servletRequest) {
this.servletRequest = servletRequest;
}
public void setServletResponse(HttpServletResponse servletResponse) {
this.servletResponse = servletResponse;
}
/**
* @see com.wondersgroup.framework.core.web.struts2.AjaxProvider#getErrorResultLocation()
*/
public String getErrorResultLocation() {
return this.errorResultLocation;
}
/**
* @see com.wondersgroup.framework.core.web.struts2.AjaxProvider#getResponseData()
*/
public String getResponseData() {
return this.responseData;
}
/**
* @see com.wondersgroup.framework.core.web.struts2.AjaxProvider#hasAjaxErrors()
*/
public boolean hasAjaxErrors() {
String object = (String)ActionContext.getContext().get("com.wondersgroup.framework.core.web.ajax.errors.flag");
return Boolean.parseBoolean(object);
}
/**
* @see com.wondersgroup.framework.core.web.struts2.AjaxProvider#isAjaxSuccess()
*/
public boolean isAjaxSuccess() {
return this.ajaxSuccess;
}
/**
* @see com.wondersgroup.framework.core.web.struts2.AjaxProvider#setAjaxSuccess(boolean)
*/
public void setAjaxSuccess(boolean ajaxSuccess) {
this.ajaxSuccess = ajaxSuccess;
}
/**
* @see com.wondersgroup.framework.core.web.struts2.AjaxProvider#setErrorResultLocation(java.lang.String)
*/
public void setErrorResultLocation(String errorResultLocation) {
this.errorResultLocation = errorResultLocation;
}
/**
* @see com.wondersgroup.framework.core.web.struts2.AjaxProvider#setResponseData(java.lang.String)
*/
public void setResponseData(String arg0) {
this.responseData = responseData;
}
protected abstract String operate();
protected abstract ValueObject getValueObject();
}
4.在实现的action中获取文件和文件名并操作:
package com.wondersgroup.hzrsmh.portal.f11010101.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.wondersgroup.framework.core.web.vo.VOUtils;
import com.wondersgroup.framework.core5.model.vo.ValueObject;
import com.wondersgroup.hzrsmh.wssip.portal.model.bo.WpsColDetail;
import com.wondersgroup.hzrsmh.wssip.portal.service.WpsColDetailService;
public class UploadFileAction extends BaseUploadFileAction{
private File file;
private String fileFileName;
private String fileContentType;
// private String result;
// private static final String prefix = "{\"success\":true,result:[";
//private static final String suffex = "]}";
WpsColDetailService colDetailService;
@Override
protected ValueObject getValueObject() {
// TODO Auto-generated method stub
return null;
}
public void setColDetailService(WpsColDetailService colDetailService){
this.colDetailService=colDetailService;
}
@Override
protected String operate() {
// TODO Auto-generated method stub
String json = null;
try {
//System.out.println(fileFileName);
String path = servletRequest.getRealPath("") + "/resource/upload/";
WpsColDetail colDetail = colDetailService.uploadFile(file,path,fileFileName);
json = String.format("{success:true,result:[{path:'%s',fileid:'%s'}]}",colDetail.getCalcfilename(),colDetail.getId());
this.servletResponse.getWriter().write(json);
this.servletResponse.getWriter().flush();
} catch (IOException e) {
e.printStackTrace();
json = "{success:false}";
try {
this.servletResponse.getWriter().write(json);
this.servletResponse.getWriter().flush();
}
catch (Exception e1) {
e1.printStackTrace();
}
}
return null;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
}
文件 上传部分事务:
public WpsColDetail uploadFile(File file,String path,String filename){
String fileName = getRandomName(filename);
String filepath = path+fileName;
String url = filepath;
url = url.replaceAll("\\\\", "/");
File saveFile = new File(new File(path),"新文件名.jpg");
if(!saveFile.getParentFile().exists()){
saveFile.getParentFile().mkdirs();
}
try
{
InputStream in = new FileInputStream(file);//把文件读入
OutputStream out = new FileOutputStream(url);//建立一个上传文件的输出流
int bytesRead;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer, 0, 1024)) != -1) {
out.write(buffer, 0, bytesRead);//将文件写入服务器
}
out.close();
in.close();
}
catch (Exception e)
{
e.printStackTrace();
}
WpsColDetailDTO colDetailDTO = new WpsColDetailDTO();
filepath="/resource/upload/"+fileName;
colDetailDTO.setCalcfilename(filepath);
WpsColDetail colDetail =ModelUtils.copyAs(colDetailDTO, WpsColDetail.class);
colDetailDao.save(colDetail);//这里存进表为了用sequence生成id
colDetail = colDetailDao.getColDetailByFilename(filepath);//用filename取数据项,感觉不太靠谱
return colDetail;
}
获取随机文件名方法:
public static String getRandomName(String filename){
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
String dateStr=dateFormat.format(new Date());
Random r = new Random();
Integer integer = new Integer(r.nextInt(10000));
String s =String.valueOf(integer);
filename = dateStr+s+filename;
return filename;
}
结束