诶诶诶略 2016-06-03 05:23 采纳率: 0%
浏览 5195
已采纳

java实现文件上传 上传成功后的文件名为什么改变了

@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public Json upload(@RequestParam(value = "imageFile") MultipartFile file,
HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String temppath = "/file";
Json j = new Json();
// 构建文件名称multipartFile
String oldName = file.getOriginalFilename();
if (!oldName.endsWith("jpg") && !oldName.endsWith("png")) {
// 判断是否是图片文件
j.setMsg("上传文件应该是jpg或png格式");
j.setSuccess(false);
return j;
}
// 获取文件的后缀
String suffix = oldName.substring(oldName.indexOf('.'));
String name = String.valueOf(System.currentTimeMillis()).concat(suffix);
String path = req.getSession().getServletContext()
.getRealPath(temppath);
try {
File filepath = new File(path);
if (!filepath.exists()) {
filepath.mkdir(); // 创建目录
}
OutputStream os = new FileOutputStream(filepath.getPath() + "/"
+ name);
InputStream is = file.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.flush();
os.close();
is.close();
j.setSuccess(true);
j.setMsg("上传成功");
} catch (Exception e) {
j.setMsg("上传失败");
j.setSuccess(false);
e.printStackTrace();
}
j.setErrorinfo(req.getContextPath() + temppath + "/" + name);
j.setObject(path + "\" + name);
return j;
}

上传后的文件:
![图片说明](https://img-ask.csdn.net/upload/201606/03/1464931428_136171.png)
  • 写回答

3条回答 默认 最新

  • threenewbee 2016-06-03 05:25
    关注

    String suffix = oldName.substring(oldName.indexOf('.'));
    String name = String.valueOf(System.currentTimeMillis()).concat(suffix);

    你这里用当前时间毫秒数(System.currentTimeMillis())作为文件名的前缀了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?