Js上传图片并生成缩略图

时间:2022-06-13 09:29:36

Js上传图片并显示缩略图的流程为
Js选择文件->Jquery上传图片->服务器接收图片流->存储图片->返回结果到Js端->显示缩略图

本文上传图片所用的Js库是ajaxfileupload,下载地址:http://files.cnblogs.com/files/yujie365/ajaxfileupload.js,Html布局采用bootstrap.
后端处理流程使用Java中的Spring框架进行处理

前面页面处理流程

1,Html页面定义File:
Js上传图片并生成缩略图

2,选择图片并上传:
绑定fileimage控件的change事件:$("#fileimage").bind("change", uploadFileImage);
上传图片:
function uploadFileImage() {
var objUrl = getObjectURL(this.files[0]);
// 上传图片
uploadFile("uploadimage/fileimage", "fileimage", function(result) {

}); 
}


//uploadUrl:服务器用于接收图片的接口
//fileElementID:file控件的id
//callback:图片上传完成后的回调方法。
function uploadFile(uploadUrl, fileElementID, callback) {
$.ajaxFileUpload({
url : uploadUrl,
secureuri : false,
type : 'post',
fileElementId : fileElementID,
dataType : 'JSON',
success : function(data) {
//data:服务器返回的结果
if (data&& callback != null) {
callback(data);
}
},
error : function(data, status, e) {

}
});
}

*显示缩略图:
更新上面uploadFileImage方法为下面代码:
function uploadFileImage() {
var objUrl = getObjectURL(this.files[0]);
// 上传图片
uploadFile("uploadimage/fileimage", "fileimage", function(result) {
// 显示缩略图
console.log("objUrl = " + objUrl);
if (objUrl) {
$("#fileimage_thumbnail").attr("src", objUrl);
}
});
}

后台Java处理流程

1,后台接收图片的方法如下:
@RequestMapping(value = "uploadimage/fileimage")
public void uploadPicture(HttpServletRequest request) {

    try {
String filePath = uploadFile(request, pictureUploadService);
if (!Tools.isEmptyString(filePath)) {
setResult(filePath);
logHelper.info("图片上传成功...");
} else {
setResult(
MessageManager.getInstance().getMessage(
"pictureuploadfailed"),
ResultType.Error);
logHelper.info("图片上传失败...");
}
} catch (IllegalStateException e) {
logHelper.warn("图片保存失败:" + e.getMessage());
} catch (IOException e) {
logHelper.warn("图片保存失败:" + e.getMessage());
}
}

2,存储图片处理流程
private String uploadFile(HttpServletRequest request,IUploadFile uploadFile) throws IllegalStateException,
IOException {
String filePath="";

    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());

if (multipartResolver.isMultipart(request)) {
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;

Iterator<String> fileNames = multipartHttpServletRequest
.getFileNames();

while (fileNames.hasNext()) {
MultipartFile file = multipartHttpServletRequest
.getFile(fileNames.next().toString());

if (file != null) {
filePath = uploadFile.uploadFile(file);
if (!Tools.isEmptyString(filePath)) {
setResult(filePath);
} else {
setResult(
MessageManager.getInstance().getMessage(
"pictureuploadfailed"),
ResultType.Error);
}
}
}
}

return filePath;
}

public interface IUploadFile {
public String uploadFile(IMultipartFile multipartFile) throws IllegalStateException, IOException ;

}

@Service
public class PictureUploadService extends BaseService implements IUploadFile {

/**
* 上传图片
* @param multipartFile
* 用户所上传的图片文件
* @return
* @throws IllegalStateException
* @throws IOException
*/
@Override
public String uploadFile(MultipartFile multipartFile) throws IllegalStateException, IOException {
String relativePath = Helpers.getImageFolderPath();

String imageSavedPath = IOTools.transferFile(multipartFile,
ConfigHelper.IMAGE_SAVED_PATH, relativePath);

logger.info("图片保存路径:" + imageSavedPath);

return imageSavedPath;
}

}

package com.weijiazhe.utils;

import java.io.File;
import java.io.IOException;
import java.util.Dictionary;

import org.springframework.web.multipart.MultipartFile;

import com.weijiazhe.weijiazheutils.ConfigHelper;

public class IOTools {

/**
* 转移文件
*
* @param multipartFile
* @param fileAbsoluteSavedPath
* @param relativePath
* @return
* @throws IllegalStateException
* @throws IOException
*/
public static String transferFile(MultipartFile multipartFile,
String fileAbsoluteSavedPath, String relativePath)
throws IllegalStateException, IOException {
if (!Tools.isEmptyString(relativePath)) {
String fileName = Tools.getGuid();
String prefix = IOTools.getPrefix(multipartFile
.getOriginalFilename());

relativePath += "\\" + fileName + prefix;

String fileSavedPath = fileAbsoluteSavedPath + relativePath;

File file = new File(fileSavedPath);

//文件不存在则创建文件.
if(!file.exists()){
//String dirName=file.getAbsolutePath();
//if(file.isDirectory()){
file.mkdirs();
//}
//fileSavedPath+="\\" + fileName + prefix;
//file=new File(fileAbsoluteSavedPath);
//file.createNewFile();
}

multipartFile.transferTo(file);
}

return relativePath;
}

}