跨域文件上傳

文件上傳的用處很大,好比上傳頭像什麼的,都須要文件上傳。javascript

今天我剛寫完文件上傳,大大小小的各類bug,我也是很苦惱。可是還好終於都寫完了。來博客分享一下。css

最重要的就是Multiparfile 和 jesyf實現跨域!html

 

須要的jar包:前端

文件上傳:com.springsource.org.apache.commons.fileupload-1.2.0.jarjava

文件的讀寫:com.springsource.org.apache.commons.io-1.4.0.jarmysql

因爲是跨服務器上傳,這裏是經過jersey實現的:jquery

jersey-client-1.18.jarweb

jersey-core-1.18.jarajax

 

在springmvc配置文件中,加上配置:spring

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<!-- 最大內存大小 -->
<property name="maxInMemorySize" value="10240"/>
<!-- 最大文件大小,-1爲不限制大小 -->
<property name="maxUploadSize" value="-1"/>
</bean>



db.properties配置文件:修改url
url=jdbc\:mysql\:///mybatis?useUnicode=true&characterEncoding=utf8


去tomcat 修改jersey服務:

 

 

咱們模擬建立一個圖片服務器,在web下建立一個存放圖片的地方(upload),而後更換端口號(別跟主工程同樣就行)

接下來運行工程,自瀏覽器打開的網頁別關。

 

而後咱們在建立一個要獲取文件的工程。這個工程必須是一個SSM。能夠運行的。

建立一個list.jsp(顯示查詢出來的數據)

建立一個UpdateUser.jsp(修改界面)

 

 

Mapper和Service層,本身寫就能夠了。就是簡單的一個修改,和查詢。

數據庫的表能夠按照個人PO類進行建立。也能夠用本身的。(圖片的字段設置null)!

 

這個是PO類。

public class Items {
private Integer id;

private String name;

private Float price;

private String pic;

private String createtime;

private String detail;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name == null ? null : name.trim();
}

public Float getPrice() {
return price;
}

public void setPrice(Float price) {
this.price = price;
}

public String getPic() {
return pic;
}

public void setPic(String pic) {
this.pic = pic == null ? null : pic.trim();
}

public String getCreatetime() {
return createtime;
}

public void setCreatetime(String createtime) {
this.createtime = createtime;
}

public String getDetail() {
return detail;
}

public void setDetail(String detail) {
this.detail = detail == null ? null : detail.trim();
}

@Override
public String toString() {
return "Items{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
", pic='" + pic + '\'' +
", createtime=" + createtime +
", detail='" + detail + '\'' +
'}';
}
}

 

 

MultipartHttpServletRequest 用於根據name名稱獲取多部件請求對象

CommonsMultipartFile 多部件請求對象,該對象能夠獲取到file文件對象信息,用於上傳文件作準備

PrintWriter 對象能夠將json對象回傳給ajax

 

步驟:

1 設置方法三個參數

2 根據input的name名獲取CommonsMultipartFile 對象

3 獲取文件上傳流

4 拼接文件名(毫秒時間+2個隨機數)

5 獲取源文件擴展名,後綴

6 建立上傳服務器文件完整路徑 Commons.PIC_HOST+"/upload/"+fileNameStr+suf

7 建立jesy服務器Clien對象,實現跨域上傳

8 開始上傳 resource.put(String.class,bytes);

9 拼接相對文件路徑,用於存儲到數據庫中

10 將完整路徑與相對路徑拼接爲json格式 String result="{\"fullPath\":\""+fullPath+"\",\"relativePath\":\""+relativePath+"\"}";

11 回傳給ajax printWriter.print(result);

 

這個是我Controller層:

@RequestMapping(value = "uploadPic",method = RequestMethod.POST)
// MultipartHttpServletRequest 用於根據name名稱獲取多部件請求對象
public void uploadPic(MultipartHttpServletRequest request, String fileName, PrintWriter printWriter){

CommonsMultipartFile cmf = (CommonsMultipartFile) request.getFile(fileName);

// 獲取文件上傳流
byte[] bytes = cmf.getBytes();

String fileNameStr = "";

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
fileNameStr = sdf.format(new Date());

System.out.println("時間戳"+fileNameStr);
Random random = new Random();
for (int i = 0; i < 3; i++) {

fileNameStr +=random.nextInt(10);

}

// 獲取文件擴展名
String originalFilename = cmf.getOriginalFilename();
String suf = originalFilename.substring(originalFilename.lastIndexOf("."));
System.out.println("獲取文件擴展名"+suf);

// 建立jesyf服務器,實現跨域上傳文件
Client client = new Client();
WebResource resource = client.resource(Commons.PIC_HOST+"/upload/"+fileNameStr+suf);

resource.put(String.class,bytes);

// 拼接圖片完整路徑
String fullPath = Commons.PIC_HOST+"/upload/"+fileNameStr+suf;
String relativePath = "/upload/"+fileNameStr+suf;

String result="{\"fullPath\":\""+fullPath+"\",\"relativePath\":\""+relativePath+"\"}";

System.out.println("完整路徑"+result);
System.out.println("完美路徑"+relativePath);

// 向頁面輸出一個json對象
printWriter.print(result);


}

 

 

這個頁面是顯示我查詢出來數據的jsp頁面。

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<%--java提供的jstl標籤庫,用於前端引入java變量--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--date類型轉換爲字符串--%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<%--<script type="text/javascript" src="/js/jquery.js"></script>--%>
<%--<script type="text/javascript" src="/js/jquery.form.js"></script>--%>

<script src="https://cdn.bootcss.com/jquery/2.2.3/jquery.js"></script>
<%--<script type="text/javascript" src="/js/jquery.form.js"></script>--%>
<script src="https://cdn.bootcss.com/jquery.form/3.49/jquery.form.js"></script>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>歡迎使用list回顯</title>

</head>
<body>
配置公共路徑:
再沒上傳圖片以前,picPath是空的。(是爲了在上傳以後,你會發現數據庫已經有了圖片路徑,到那時頁面沒顯示,就須要這句話。)
<c:set var="picPath" value="http://127.0.0.1:8082/"></c:set>
<table border="2px" cellpadding="0px" cellspacing="0px" width="1000px" >
<tr>
<th>編號</th>
<th>姓名</th>
<th>價格</th>
<th>詳情</th>
<th>商品圖片</th>
<th>日期</th>
</tr>

<c:forEach items="${itemsList}" var="items">

<tr>
<td>${items.id}</td>
<td>${items.name}</td>
<td>${items.price}</td>
<td>${items.detail}</td>
<td><img src="${picPath}${items.pic}" alt="" width="100" height="100"></td>
<td>
${items.createtime}
</td>
<td>                                                   
<a href="${pageContext.request.contextPath}/upload/updateUser.do?id=${items.id}&picPath=${picPath}">修改</a>
</td>
<td>
<a href="javascript:void(0);" onclick="btnAction(${user.id})">刪除</a>
</td>
</tr>

</c:forEach>
</table>
</body>
</html>

 

 

ajax使用的是:

jQuery Form插件是一個優秀的Ajax表單插件,能夠很是容易地、無侵入地升級HTML表單以支持Ajax。

jQuery Form有兩個核心方法 – ajaxForm() 和 ajaxSubmit(), 它們集合了從控制表單元素到決定如何管理提交進程的功能

使用JQuery的$.ajax()會報錯。

若是使用$.ajax()請求,則提交的Request類型最終爲RequestFacade,而不是MultipartHttpRequest

 

這個是個人修改界面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<title>Title</title>
<%--<script type="text/javascript" src="/js/jquery-1.8.3.min.js"></script>--%>
<script src="https://cdn.bootcss.com/jquery/2.2.3/jquery.js"></script>
<%--<script type="text/javascript" src="/js/jquery.form.js"></script>--%>
<script src="https://cdn.bootcss.com/jquery.form/3.49/jquery.form.js"></script>
<script type="text/javascript">

function submitImgSize1Upload(){
// alert('你是豬嗎'); 驗證是否走了點擊事件
var option={
url:'${pageContext.request.contextPath }/upload/uploadPic.do',
type:'POST',
dataType:'text',
data:{
fileName : 'imgSize1File' 將選取的圖片路徑傳到後臺進行處理。
},
success:function(data){

alert(data);

//把json格式的字符串轉換成json對象
var jsonObj = $.parseJSON(data);

// 經過input標籤設置的ID,把圖片路徑fu gei
//返回服務器圖片路徑,把圖片路徑設置給img標籤(顯示修改頁面的圖片)
$("#imgSize1ImgSrc").attr("src",jsonObj.fullPath);
//數據庫保存相對路徑,在圖片的input標籤內加上Id,把imgSize1寫到id內
//把路徑傳到後臺,添加到數據庫中。
$("#imgSize1").val(jsonObj.relativePath);
},

};

//拿到form表單對象,提交表單
$("#itemForm").ajaxSubmit(option);

}
</script>


</head>
<body>
                                                          這個屬性是文件上傳必須用到的
<form id="itemForm" action="${pageContext.request.contextPath}/upload/updateById.do" method="post" enctype="multipart/form-data">

<input type="hidden" name="id" value="${items.id}">
姓名:
<input type="text" name="name" value="${items.name}">
<br>
價格 : <input type="text" name="price" value="${items.price}">
<br>
描述 : <input type="text" name="detail" value="${items.detail}">
<br>
商品圖片: <img id='imgSize1ImgSrc' src='${picPath}${items.pic}' height="100" width="100" /><br> 
圖片路徑: <input id="imgSize1" type="text" name="pic" value="${items.pic}"><br>
日期 :<input type="text" name="createtime" value="${items.createtime}"><br>
<input type='file' id='imgSize1File' name='imgSize1File' class="file" onchange='submitImgSize1Upload()'/>

<input type="submit" value="提交">
</form>

</body>
</html>

 

 

 

 

這個是Maven版本的須要導入的依賴:

 

相關文章
相關標籤/搜索