当前位置: 代码迷 >> Java Web开发 >> 请教一个上传文件功能,有有关问题,名字有了文件没上传成功,WEB,SPRING框架的
  详细解决方案

请教一个上传文件功能,有有关问题,名字有了文件没上传成功,WEB,SPRING框架的

热度:81   发布时间:2016-04-17 12:15:22.0
请问一个上传文件功能,有问题,名字有了文件没上传成功,WEB,SPRING框架的
Action里面
  private File file;
  private String fileFileName;
  private String fileContentType;
public String execute() throws Exception {
try{
Date nowTime=new Date(); //系统时间
SimpleDateFormat m=new SimpleDateFormat("yyyyMMddhhmmss");
String picname=String.valueOf(m.format(nowTime));//将系统时间转换为字符型
String picpath=picname+1+".gif";
//......................................................
HttpServletRequest request=ServletActionContext.getRequest();
ActionContext context = ActionContext.getContext();
  context.getValueStack();
  String filename=picname+1+".gif";
String inputpath = "../Fitment/images/product";
picpath="/Fitment/images/product/"+filename; 
String realpath = request.getRealPath(inputpath);
// System.out.println(fileFileName);
if(fileFileName!=null)
  {
  File target = new File(realpath+"/"+filename);
  if (target.exists()) {
  target.delete();
  }
  file.renameTo(target);
  }
Map map = new HashMap();
map.put("picture1",picpath);
pictureService.addClient1(map);
return SUCCESS;
} catch (DataAccessException dae) {
info.setErrmsg(dae.getMessage());
} catch (Exception e) {
info.setErrmsg(e.getMessage());
}return ERROR;
}

public Object getModel() {
return info;
}

public void setPictureService(PictureService pictureService) {
this.pictureService = pictureService;
}

public void setFile(File file) {
this.file = file;
}

public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}

public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
JS里面的
if(document.all.pic1.value=='')
{
alert("请插入商家图片!")
return;
}

var x = document.getElementById("file1"); 
var y = document.getElementById("pic1");
if(!x || !x.value || !y)

return;
var patn = /\.jpg$|\.bmp$|\.gif$/i; if(patn.test(x.value))
{ y.src = "file://localhost/" + x.value; }
else{ 
alert("您选择的似乎不是图像文件。")
return;
}

页面内容
<td width="14%" height="19" align="left"><nobr>商家图片</nobr></td>
<td><table><tr>  
  <td width="40%">
  <DIV align=center>
  <IMG id="pic1" height=100 width=100 src="../../images/userindex/addproduct/detail_no_pic.gif">
  </DIV>
  </td>
  <td width="46%" height="19" align="left" > 
<input type=file name=file size=50 id="file1" onchange="preview1()">
  </td>

Action配置内容里面加了
<interceptor-ref name="fileUploadStack"></interceptor-ref>

有这个类
package Fitmenthoutai.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Uploadfile {
// <interceptor-ref name="fileUploadStack"></interceptor-ref> 
File file;
public String uploadfile(String filename) throws IOException
{
if(file.length()>1000000)

{
return "fail";
}
FileOutputStream outputStream = new FileOutputStream("filename"); 
  相关解决方案