關於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