剛從ruby轉做java,分個活做照片上傳,開始感覺很崩潰,以為本人菜鳥一個,一見到流什麼的就感覺很牛逼的東西我怎麼會啊,自學加百度,做出來了,兩種方法完成,關于js預覽就不上傳了,留作以後備用,也能幫助下和我一樣的菜鳥
jsp頁面
<form action="uploadPhoto.do" method="post" enctype="multipart/form-data">
上傳照片:<input type=file name="file" id="file" onchange="javascript:upload();">
<p><div id="localImag"><img id="preview" width=-1 height=-1 style="diplay:none" /></div></p>
<img id="p_w_picpathp" style="display:none" src="<%=path%>/<%=realPath%>" width="300px;" height="350px;"/><br/>
<input type="p_w_picpath" src="./p_w_picpaths/bto2.jpg"> //上傳按鈕
</form>
/**
* 照片上傳
* @author sixd
* @throws IOException
* @throws ServletException
*
*/
@RequestMapping(value = "/uploadPhoto.do")
public void uploadPhoto(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse response) throws Exception {
InputStream is = null;
OutputStream os = null;
List<Map<String,Object>> zplist = null;
String responseText = "";
String changName = "";
String realPath = "";
String xh = (String) request.getSession().getAttribute("xh");
String path = request.getSession().getServletContext().getRealPath("drzp");
String fileName = file.getOriginalFilename();
try {
zplist = zpscDao.findZpInfo(xh);
int index = fileName.lastIndexOf(".");
String endFlag = fileName.substring(index);
changName = xh.concat(endFlag);
File a = new File(path);
if (!a.exists()) {
//建立目錄
a.mkdir();
}
is = file.getInputStream();
os = new FileOutputStream(path+"\\"+changName);
int len = 0;
byte[] bytes = new byte[1024];
while((len = is.read(bytes))>0){
os.write(bytes, 0, len);
}
realPath = "drzp/"+changName+"";
if(zplist != null && !zplist.isEmpty()){
zpscDao.updatePhotoPath(realPath);
}else{
zpscDao.savePhotoPath(xhgh,realPath);
}
responseText="success";
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
responseText="fail";
}finally{
is.close();
os.close();
}
response.sendRedirect("sczp/zpsc.jsp?path="+realPath+"&responseText="+responseText+"");
}
方法二、
/**
* 上傳照片
* @author sixd
* @throws IOException
* @throws ServletException
*
*/
@RequestMapping(value = "/uploadPhoto.do")
public void uploadPhoto(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse response) throws Exception {
Map<String, Object> map = null;
List<Map<String,Object>> zplist = null;
String responseText = "";
String xhgh = (String) request.getSession().getAttribute("xh")
try {
map = zpscDao.findStudentInfo(xh);
zplist = zpscDao.findZpInfo(xh);
if(map != null && map.size()>0){
String fileName = file.getOriginalFilename();
int index = fileName.lastIndexOf(".");
String endFlag = fileName.substring(index);
String changName = xhgh.concat(endFlag);
System.out.println(path);
File targetFile = new File(path, changName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
file.transferTo(targetFile);
String realPath = "xxxx"/"+changName+"";
if(zplist != null && !zplist.isEmpty()){
zpscDao.updatePhotoPath(realPath);
}else{
zpscDao.savePhotoPath(xh,realPath);
}
}
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
}
response.sendRedirect("sczp/zpsc.jsp");
}
方法三、上傳到資料裡blob型
主要借鑒http://www.myexception.cn/database/628584.html
1.導入commons-fileupload-1.2.1.jar
2.配置上傳<!-- 支援上傳檔案 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
3.jsp:
<form method="post" action="uploadp_w_picpath.do" name="form" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" name="sub" value="上傳">
</form>
4.控制器:
@RequestMapping(value = "/uploadp_w_picpath.do")
public void uploadPhoto(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse response) throws Exception {
try{
byte[] data = file.getBytes();
int id = uploadDao.FileUpload(data, file.getOriginalFilename());
}
catch(Exception e){
e.printStackTrace();
}
}
5.接口實作
public int FileUpload(byte[] data, String originalFilename) {
String sql = "insert into img (img,name) VALUES (?,?)"; img blob
Connection conn=null;
try {
conn = jdbcTemplate.getDataSource().getConnection();
PreparedStatement ps=conn.prepareStatement(sql);
//注意 :大對象類型的 我們存入的是bytes[],這裡要set object
ps.setObject(1, data);
ps.setString(2, originalFilename);
ps.executeUpdate();
conn.commit();
ps.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
上邊這種寫法比較笨,不想spring的
找到一個api但是因為沒有時間,是以沒有試着做一下,但是例子在下邊,應該不難
http://docs.spring.io/spring/docs/1.1.4/api/org/springframework/jdbc/core/support/AbstractLobCreatingPreparedStatementCallback.html
- public abstract class AbstractLobCreatingPreparedStatementCallback
- extends Object
- implements PreparedStatementCallback
Abstract PreparedStatementCallback implementation that manages a LobCreator. Typically used as inner class, with access to surrounding method arguments.
Delegates to the
setValues
template method for setting values on the PreparedStatement, using a given LobCreator for BLOB/CLOB arguments.
A usage example with JdbcTemplate:
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); // reusable object
LobHandler lobHandler = new DefaultLobHandler(); // reusable object
jdbcTemplate.execute(
"INSERT INTO p_w_picpathdb (p_w_picpath_name, content, description) VALUES (?, ?, ?)",
new AbstractLobCreatingPreparedStatementCallback(lobHandler) {
protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException {
ps.setString(1, name);
lobCreator.setBlobAsBinaryStream(ps, 2, contentStream, contentLength);
lobCreator.setClobAsString(ps, 3, description);
}
}
);