关于form表单上传图片的一些记录


jsp页面

<form class="form-horizontal" role="form"
action="brandAction_addBrandMes" method="post" enctype="multipart/form-data">

<div class="form-group">
<label for="picPath" class="col-sm-3 control-label">品牌大图:</label>
<div class="col-sm-5">
<input type="file" id="picPath" name="pp" placeholder="请上传...">
</div>
</div>

<div class="form-group">
<div class="col-sm-offset-5 col-sm-10">
<button type="submit" class="btn btn-primary">确定添加</button>
<button type="reset" class="btn btn-primary">重置</button>
</div>
</div>
</form>

action后台

private String ppFileName;// 品牌大图名(命名规则:input中的name值+FileName
private File pp;//品牌大图(命名规则:input中的name值

后台解析代码

public String getPicturePatch(String fileName, File file, String folderName) throws IOException {
String newPath = "";
if (fileName != null && !"".contentEquals(fileName)) {
String picName = new Date().getTime() + fileName.substring(fileName.lastIndexOf("."), fileName.length());//当前时间+图片后缀
String path = new File(ServletActionContext.getServletContext().getRealPath("/")).getParentFile() + "/"
+ folderName + "/";  //文件要保存的位置
File saved = new File(path);
InputStream ins = null;
OutputStream ous = null;
if (!saved.exists()) {
saved.mkdirs();
}
try {
ins = new FileInputStream(file);
ous = new FileOutputStream(new File(path, picName));

byte[] b = new byte[1024];
int len = 0;

while ((len = ins.read(b)) != -1) {
ous.write(b, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ous != null)
ous.close();
if (ins != null)
ins.close();
}

HttpServletRequest req = ServletActionContext.getRequest();
String serverPath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/";
newPath = serverPath + folderName + "/" + picName;
}
return newPath;
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM