最近写了个上传下载。
// 文件路径
private File file;
private String fileFileName;
private String fileContentType;
private String msg;
@Autowired
private FileUploadService fileService;
private static final String upPath = CommonUtil.getProsValue("UPLOAD_PATH");
/**
* 上传
*/
@Action(value = "upload", results = {@Result(name = "upload", location = "/jsp/upload.jsp")})
public String upload()
throws Exception
{
String upFlag = this.getRequest().getParameter("upFlag");
try
{
if (null != file)
{
Annex annex = new Annex();
annex.setAnnexId(CommonUtil.getUuid());
annex.setAnnexName(fileFileName);
annex.setCrtDate(new Date());
annex.setCrtUser("xiao");
if ("1".equals(upFlag))
{
// 转为blob存到数据库
Blob blob = upToOracle();
annex.setAnnexCont(blob);
}
else
{
// 上传至服务器上
// String path = request.getSession().getServletContext().getRealPath(upPath);
String path = upPath;
upFilePath(path);
annex.setAnnexPath(path + "/" + fileFileName);
}
fileService.saveAnnex(annex);
}
}
catch (Exception e)
{
System.out.println("上传附件错误。");
}
return "upload";
}
/**
* 转为blob存到数据库
*
* @throws IOException
*/
private Blob upToOracle()
throws IOException
{
FileInputStream fis = new FileInputStream(file);
Blob blob = Hibernate.createBlob(fis);
fis.close();
return blob;
}
/**
* 上传至服务器上
*/
private void upFilePath(String path)
throws Exception
{
File fosFile = new File(path);
// 上传文件夹不存在时如何自动创建文件夹
if (!fosFile.exists())
{
fosFile.mkdirs();
}
System.out.println(path);
FileOutputStream fos = new FileOutputStream(path + "/" + fileFileName);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0)
{
fos.write(buffer, 0, len);
}
fis.close();
fos.close();
}