1.项目列表,页面点击上传,只上传到target中的upload中,无法上传到项目中的upload中。
2.这是点击上传图片确认后控制台显示。
3.上传图片controller层的内容。
public ResultMessage photoUpload( MultipartFile file, HttpSession session ) throws Exception {
String realPath = session.getServletContext().getRealPath("/media/upload");
String uuid = UUID.randomUUID().toString();
String[] strings = file.getOriginalFilename().split("\\.");
String fileName=uuid+"."+strings[strings.length - 1];
System.out.println("文件名"+fileName);
realPath=realPath+"\\"+fileName;
System.out.println("真实的上传文件的路径"+realPath);
file.transferTo(new File(realPath));
System.out.println("上传文件成功");
ResultMessage resultMessage = new ResultMessage(200,fileName);
return resultMessage;
4.jsp执行上传图片的代码
<div class="layui-form-item">
<label class="layui-form-label">照片</label>
<button type="button" class="layui-btn" id="upfile">
<i class="layui-icon"></i>上传图片
</button>
<input type="hidden" name="photo" id="p1">
<div class="layui-input-block">
<img alt="个人一寸照片" src="/media/images/obj.jpg" id="img1" width="200px" height="300px">
</div>
</div>
<div class="layui-form-item">
<input class="layui-btn" style="margin-left: 10%" id="btn1" disabled="disabled" type="button" value="确认新增" onclick="addEmp();">
</div>
var uploadInst = upload.render({
elem: '#upfile' //绑定元素
,url: '/photoUpload' //上传接口地址
,done: function(obj){
lay.msg("上传成功");
//上传完毕回调
console.log(obj);
if(obj.status==200){
$("#p1").val(obj.message);//藏值
$("#img1")[0].src="/media/upload/"+obj.message; //图片回显
$("#btn1").attr("disabled",false); //如果图片不上传,新增按钮就是禁用状态
}
}
,error: function(){
//请求异常回调
}
});
5.页面
如何才能上传成功并显示图片,求大神指点!!!
因为程序运行时并不是运行你源代码,而是target,所以当你上传图片时,类加载器对应的资源目录地址其实是指向了target的。
如果你的图片位于 没有权限验证的话,只需要把路径对好就可以了
但看上去你好像获取不到, 所以读取图片还需要一个 controller 方法
以下代码作为下载或读取文件的参考 路径你自己调整一下应该就可以了
@RequestMapping("download/{fileName:.+}")
public String download(@PathVariable("fileName") String fileName, HttpServletResponse response) {
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
try {
//其他方法在打包后的liunx系统会报错
ClassPathResource resource = new ClassPathResource("/media/upload"+ File.separator + fileName);
InputStream inputStream = resource.getInputStream();
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
os.flush();
// 这里主要关闭。
os.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}