Jersey中通过ajax进行文件上传
程序员文章站
2022-04-20 21:10:15
...
一.Rest接口:
package com.zjtachao.wcad.dsp.cs.rest.resource; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Calendar; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.apache.commons.io.FileUtils; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataParam; import com.zjtachao.framework.common.util.json.JsonObject.ResultCode; import com.zjtachao.framework.common.util.rest.RestContents; import com.zjtachao.framework.common.util.tools.UploadFileUtil; import com.zjtachao.framework.pojo.rest.RestObject; import com.zjtachao.wcad.dsp.cs.pojo.ro.DspCsMaterialImgRo; import com.zjtachao.wcad.dsp.cs.rest.resource.base.BaseResource; import com.zjtachao.wcad.dsp.cs.util.constants.DspCsCommonConstants; import com.zjtachao.wcad.dsp.cs.util.tools.DspCsValidateUtil; @Path("/upload") public class DspAdUploadResourceImpl extends BaseResource { /** * 使用普通的流的形式上传:调用UploadFileUtil.uploadImage * @param filename * @param uploadedInputStream * @param fileDetail * @return */ @POST @Path("/file") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(RestContents.MEDIA_TYPE_APPLICATION_JSON_UTF8) public RestObject<DspCsMaterialImgRo> uploadFile( @FormDataParam("file") InputStream uploadedInputStream,@FormDataParam("file") FormDataContentDisposition fileDetail) { RestObject<DspCsMaterialImgRo> rest = new RestObject<DspCsMaterialImgRo>(); rest.setCode(ResultCode.VALID_NO_PASS.getCode()); try{ if((null != uploadedInputStream) && (null != fileDetail)){ String fileName = fileDetail.getFileName(); //验证格式是否正确(支持 jpg/png/gif) if(DspCsValidateUtil.validateImgFileType(fileName)){ //获取图片本地路径 String imgPath = configUtil.getConfigByKey(DspCsCommonConstants.COM_ZJTACHAO_WCAD_MATERIAL_IMG_PATH); //上传之后的相对路径 String filePath = UploadFileUtil.uploadImage(imgPath, uploadedInputStream, fileName); //上传之后的URL String headImgUrl = configUtil.getConfigByKey(DspCsCommonConstants.COM_ZJTACHAO_WCAD_MATERIAL_IMG_URL_PREFIX); //返回物料对象 DspCsMaterialImgRo ro = new DspCsMaterialImgRo(); ro.setMaterialImgUrl(headImgUrl+filePath); rest.setCode(ResultCode.SUCCESS.getCode()); rest.setMsg("上传成功!"); rest.setRst(ro); }else{ rest.setMsg("上传失败!原因:图片格式只能为jpg、png、gif格式!"); } }else{ rest.setMsg("上传失败!原因:图片数据不能为空!"); } }catch(Exception ex){ rest.setCode(ResultCode.ERROR.getCode()); rest.setMsg("上传失败!原因:服务器出错!"); logger.error("上传物料失败!",ex); } return rest; } /** * 使用FileUtils.copyInputStreamToFile方式上传 * * @param fileInputStream * @param disposition * @return */ @POST @Path("uploadimage1 ") @Consumes(MediaType.MULTIPART_FORM_DATA) public String uploadimage1(@FormDataParam("file") InputStream fileInputStream, @FormDataParam("file") FormDataContentDisposition disposition) { String imageName = Calendar.getInstance().getTimeInMillis() + disposition.getFileName(); File file = new File(imageName); try { //使用common io的文件写入操作(注:需要2.2以上版本的commons-io包) FileUtils.copyInputStreamToFile(fileInputStream, file); //原来自己的文件写入操作 //saveFile(fileInputStream, file); } catch (IOException ex) { //TODO } return "images/" + imageName; } // 保存文件信息到磁盘 private void saveFile(InputStream uploadedInputStream, File file) { try { OutputStream outpuStream = new FileOutputStream(file); int read = 0; byte[] bytes = new byte[1024]; //outpuStream = new FileOutputStream(new File(serverLocation)); while ((read = uploadedInputStream.read(bytes)) != -1) { outpuStream.write(bytes, 0, read); } outpuStream.flush(); outpuStream.close(); } catch (IOException e) { e.printStackTrace(); } } }注意:若使用FileUtils.copyInputStreamToFile方式,需要2.2以上版本的commons-io包
如下:
<!-- Apache Commons --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.2</version> </dependency>
二.UploadFileUtil文件上传工具类:
package com.zjtachao.framework.common.util.tools; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Calendar; /** * 上传文件工具类 */ public class UploadFileUtil { /** * 上传图片的方法 * @param imageFile * @param imageName * @return * @throws IOException */ public static String uploadImage(String path, File imageFile, String imageName) throws IOException { /*创建输入流*/ InputStream is = new FileInputStream(imageFile); return uploadImage(path, is, imageName); } /** * * 上传图片的方法 * @param path * @param inputStream * @param imageName * @return * @throws IOException */ public static String uploadImage(String path, InputStream inputStream, String imageName) throws IOException { int random = (int)(Math.random()*900)+100; /*设置上传目录*/ Calendar cal=Calendar.getInstance(); String month = String.valueOf(cal.get(Calendar.MONTH)+1); month = month.length() == 1 ? "0" + month : month; String day = String.valueOf(cal.get(Calendar.DAY_OF_MONTH)); day = day.length() == 1 ? "0" + day : day; String imageUrlPath = "images" + "/" + cal.get(Calendar.YEAR) + "/" + month + "/" + day; String imagePath = path + imageUrlPath; File file = new File(imagePath); if (!file.exists()) { file.mkdirs(); } /*设置目标文件*/ String targetImageName = "" + cal.get(Calendar.HOUR) + cal.get(Calendar.MINUTE) + cal.get(Calendar.SECOND) + cal.get(Calendar.MILLISECOND) + random + imageName.substring(imageName.lastIndexOf(".")); File target = new File(imagePath + "/" + targetImageName); /*创建输出流*/ OutputStream os = new FileOutputStream(target); byte[] buffer = new byte[1024]; int length = 0; while ((length = inputStream.read(buffer)) > 0) { os.write(buffer, 0, length); } inputStream.close(); os.close(); return "/" + imageUrlPath + "/" + targetImageName; } }
三.DspValidateUtil验证工具类:
/** * * 验证图片类型 * @param fileName * @return */ public static boolean validateImgFileType(String fileName){ boolean flag = false; if((null != fileName) && (!"".equals(fileName))){ int index = fileName.lastIndexOf("."); if(index > 0){ String type = fileName.substring(index+1); if((null != type) && (type.equalsIgnoreCase("jpg") || type.equalsIgnoreCase("png") || type.equalsIgnoreCase("gif"))){ flag = true; } } } return flag; }
三.Form表单:
<form id="form" enctype="multipart/form-data" method="post" action="${base}/news/addImage"> <div> <div id="imageDiv"> <input id="image" name="file" title="上传图片" type="file" multiple accept="image/*" onchange="handleFiles(this)"> <input type="button" value="删除" onclick="deleteImage()"/> </div> <div id="previewImage" align="center"></div> </div> <input type="button" value="保存" class="btn btn-large btn-danger" onclick="doSubmit()"/> <input id="size" type="hidden"/> </form>
四.普通上传——form表单提交方式:
function doSubmit(){ var size = $("#size").val(); if(size > 104857600){ $("#msg").text("上传的图片尺寸过大"); return; } $("#form").submit(); }
五.Ajax上传:
function upload(obj) { var formData = new FormData($("#form")[0]); $.ajax({ url: "http://192.168.1.1/webapp/rest/upload/image", type: "POST", data: formData, async: false, cache: false, contentType: false, processData: false, success: function (data) { //预览 previewImage(obj); } }); }
六.预览:
function handleFiles(obj) { var files = obj.files; var size = files[0].size; $("#size").val(size); img = new Image(); if(window.URL){ img.src = window.URL.createObjectURL(files[0]); img.onload = function(e) { window.URL.revokeObjectURL(this.src); } $("#previewImage").append(img); }else if(window.FileReader){ var reader = new FileReader(); reader.readAsDataURL(files[0]); reader.onload = function(e){ img.src = this.result; $("#previewImage").append(img); } }else{ obj.select(); obj.blur(); var nfile = document.selection.createRange().text; document.selection.empty(); img.src = nfile; img.onload=function(){ } $("#previewImage").append(img); } }
参考:
推荐阅读
-
在jquery中的ajax方法怎样通过JSONP进行远程调用
-
MVC中基于Ajax和HTML5实现文件上传功能
-
jQuery实现文件编码成base64并通过AJAX上传的方法
-
通过Ajax方式上传文件使用FormData进行Ajax请求
-
jquery中的ajax方法怎样通过JSONP进行远程调用
-
使用FormData进行Ajax请求上传文件
-
php中通过Ajax如何实现异步文件上传的代码实例
-
使用Ajax进行文件与其他参数的上传功能(java开发)
-
使用FormData进行Ajax请求上传文件的实例代码
-
(火狐浏览器)前端以FormData类形成表单(含文件),通过ajax提交,PHP后端iconv()报“文件名含有非法字符”且POST中的‘Ttitle’丢失