两种思路:
一种用一个变量保存。
代码如下:
@Value("#{conf.appendixPath}")
private String appendixPath;
/具体添加
@RequestMapping(value="/projectDetailAdd", method=RequestMethod.POST)
public ModelAndView orgAdd(ProjectDetail projectDetail,HttpServletRequest request,HttpServletResponse response,@RequestParam(value = "filePath", required = false) MultipartFile file) throws ParseException {
/*
* 1获取参数
* 2转换
* 3赋值
*/
//获取参数
//转换
//赋值
String did = request.getParameter("did");
if(projectDetail.getDid()==null)
{
projectDetailService.add(projectDetail);
//上传文件
if (file != null && file.getSize() > 0) {
try {
String pathString = saveFileToServer(file, appendixPath, "detail_"+projectDetail.getDid());
projectDetail.setPath(pathString);
projectDetailService.update(projectDetail);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
if (file != null && file.getSize() > 0) {
try {
String pathString = saveFileToServer(file, appendixPath, "detail_"+projectDetail.getDid());
projectDetail.setPath(pathString);
projectDetailService.update(projectDetail);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
//当文件为空,则保存原来数据
String pathBack = request.getParameter("pathBack");
projectDetail.setPath(pathBack);
}
projectDetailService.update(projectDetail);
}
ModelAndView view = new ModelAndView("projectDetail", "message", "");
return view;
}
saveFileToServer方法
//上传文件
private String saveFileToServer(MultipartFile multifile, String path, String carId)
throws IOException {
// 创建目录
File dir = new File(path);
if (!dir.exists()) {
dir.mkdir();
}
// 读取文件流并保持在指定路径
InputStream inputStream = multifile.getInputStream();
String fileName = multifile.getOriginalFilename();
String[] fileNameArr = fileName.split("\\.");
OutputStream outputStream = new FileOutputStream(path
+carId +"." + fileNameArr[1]);
byte[] buffer = multifile.getBytes();
int bytesum = 0;
int byteread = 0;
while ((byteread = inputStream.read(buffer)) != -1) {
bytesum += byteread;
outputStream.write(buffer, 0, byteread);
outputStream.flush();
}
outputStream.close();
inputStream.close();
return path + carId +"." + fileNameArr[1];
}
HTML主要代码
<input name="pathBack" type="text" class="input-style1" id="pathBack" value="${projectDetail.path}" />
<input id="filePath" type="file" name="filePath"/>
另外一种办法从数据库中取出数据保存出来,然后再赋值,最后UPDATE。