ajaxFileUploadアップロード画像プレビューまとめ
5380 ワード
背景:私たちは普段、プロジェクトをしているときに、必ずアイコン、画像、ファイルなどの非同期アップロード機能に遭遇します.今日はajaxFileuploadコンポーネントのアイコンアップロードを例に、このコンポーネントの使い方をまとめてみましょう.
Tips:私は以前のブログで3つのアップロードコンポーネントを共有しましたが、実は主なコードはすでにこの文章で体現されています.今日ajaxfileuploadというコンポーネントをもう一度まとめてみると、高バージョン(1.9以上)のJqueryの下でajaxfileuploadが異常を示していることに気づきました.それからajaxfileuploadのjQueryオブジェクトを$に置き換えて使用できました.ajaxFileUploadに対してこの間違いjQueryを報告しました.handleError is not a function、ここ、そうここを突き刺してください.添付ファイルは使用可能なajaxfileuploadを修正します.jsファイル.
需要:カスタムスタイル[アップロード]ボタンをクリックしてから[アップロード]ボタンをクリックして、ファイル選択ダイアログボックスを開き、ファイルを選択して自動的にアップロードし、その画像をプレビューすることができます.
分析:
1.【アップロード】ボタンはaリンクですが、アップロードファイルには必ずinput type=「file」の要素が必要です.aリンクという「アップロード」ボタンをクリックすると、input type=「file」要素をトリガーするclickメソッドがファイル選択ダイアログボックスを開き、ファイルを選択すると、input type=「file」のonchangeメソッドがトリガーされ、ajaxfileuploadのアップロードメソッドが呼び出されてアップロードが開始されます.
2.サーバ側は、このファイルデータを受信してファイルサーバに保存し、このファイルの相対パスを返し、非表示ドメインに挿入し、最後にフォームをコミットすると、この相対パスをバックグラウンドにコミットして入庫を保存します.
3.プレビューは、画像のストリームデータを取得して画像を表示します.
使用するテクノロジー:jquery,ajaxfileupload,springMVC
コード:
1.HTMLクリップ
<div class="uploadPicture">
<img id="imgHead" src="" width="106" height="122" alt=" ">
<input type="file" onchange="uploadHead();" id="basicInfoHead" style="display:none;"
name="basicInfoHead" />
<input type="hidden" id="basicHeadUrl" >
<a href="#basicInfo" id="uploadBasicInfoHead" > </a>
</div>
2.JSコード
// , click
$('#uploadBasicInfoHead').on('click',function(){
$('#basicInfoHead').click();
});
function uploadHead(){
$.ajaxFileUpload({
url:"${pageContext.request.contextPath}/profile/uploadBasicHead",//
secureuri:false,
fileElementId:"basicInfoHead",// id
dataType: 'json', //json
success: function (data) {
$("#imgHead").attr("src","${pageContext.request.contextPath}/profile/readImage?imagePath="+data.imagePath);
$('#basicHeadUrl').val(data.imagePath);
},error:function(XMLHttpRequest, textStatus, errorThrown){
alert(' !');
}
});
};
3.JAVAコード
//
@RequestMapping(value = "profile/uploadBasicHead", produces = "text/plain;charset=UTF-8")
@ResponseBody
public String ajaxUpload(HttpServletRequest request) throws IllegalStateException,
IOException {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
String fileName = "";
String uploadPath = "uploadFile/head/";
String path =request.getSession().getServletContext().getRealPath("/")+uploadPath;
/*File uploadPathFile = new File(path);
if (!uploadPathFile.exists()) {
uploadPathFile.mkdir();
}*/
String realPath = "";
for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {
String key = (String) it.next();
MultipartFile mulfile = multipartRequest.getFile(key);
fileName = mulfile.getOriginalFilename();
fileName = handlerFileName(fileName);
File file = new File(path + retFileName);
mulfile.transferTo(file);
}
realPath = "{\"imagePath\":\""+uploadPath+fileName+"\"}";
return realPath;
}
//
private String handlerFileName(String fileName) {
// start
fileName = (new Date()).getTime()+"_"+fileName;
// + ,
String pre = StringUtils.substringBeforeLast(fileName, ".");
String end = StringUtils.substringAfterLast(fileName, ".");
fileName = Digests.encodeByMd5(pre)+"."+end;// MD5 ,
// end
return fileName;
}
// ,
@RequestMapping(value = "profile/readImage", produces = "text/plain;charset=UTF-8")
public void readImage(HttpServletRequest request, HttpServletResponse response){
String imagePath = request.getSession().getServletContext().getRealPath("/")+request.getParameter("imagePath");
try{
File file = new File(imagePath);
if (file.exists()) {
DataOutputStream temps = new DataOutputStream(response
.getOutputStream());
DataInputStream in = new DataInputStream(
new FileInputStream(imagePath));
byte[] b = new byte[2048];
while ((in.read(b)) != -1) {
temps.write(b);
temps.flush();
}
in.close();
temps.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}