jquery上传图片并回显
在工作中,有时候我们会遇到这样的情况:上传图片并回显。先来看看代码怎么写。然后咱们在讨论,这个案例中使用到的技术。页面是用的是thymeleaf开发的。说明:页面中必须引入query上传的div:<div class="form-group"> <label class=
在工作中,有时候我们会遇到这样的情况:上传图片并回显。
先来看看代码怎么写。然后咱们在讨论,这个案例中使用到的技术。
页面是用的是thymeleaf开发的。
说明:页面中必须引入query
上传的div:
<div class="form-group">
<label class="col-sm-3 control-label">图片:</label>
<div class="col-sm-8" >
<input type="hidden" name="name" id="productImgValue" th:field="*{productImg}">
<img height='65' width='55' id="showImgId" th:src="@{${orderTemp.productImg}}" style="display:none">
<input type="file" name="photo" id="photo" value="" placeholder="上传商品图片">
<input type="button" onclick="postData(0);" value="上传" name="" style="width:100px;height:30px;">
</div>
</div>点击上传按钮的js:
/**
* 如果图片不为空的话,就显示图片
* */
$(document).ready(function () {
var productImgValue = $("#productImgValue").val();
if(null != productImgValue && '' != productImgValue){
$("#showImgId").show();
}
});
function postData(type){
var formData = new FormData();
formData.append("file",$("#photo")[0].files[0]);
$.ajax({
url:'/order/temp/upload/productImg', /*接口域名地址*/
type:'post',
data: formData,
contentType: false,
processData: false,
success:function(res){
console.log(res);
var code = res.code;
if(0== code ){
$("#productImgValue").val(res.url);
//回显图片
$("#showImgId").attr('src',res.url);
if(type ==0 ){
//显示
$("#showImgId").show();
}
}else {
alert(res.msg);
}
}
})
}看看后台怎么写的:
@PostMapping("/upload/productImg")
@ResponseBody
public AjaxResult productImg(@RequestParam(value="file",required=false) MultipartFile file) throws Exception
{
try
{
String fileName = FileUploadUtils.uploadWithPath(poiExcelImgFilePath, file);
String url = serverConfig.getUrl() + fileName;
AjaxResult ajax = AjaxResult.success();
ajax.put("fileName", fileName);
ajax.put("url", url);
return ajax;
}
catch (Exception e)
{
return AjaxResult.error(e.getMessage());
}
}
}工具类FileUploadUtils:
package com.ruoyi.common.utils.file;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.file.FileNameLengthLimitExceededException;
import com.ruoyi.common.exception.file.FileSizeLimitExceededException;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
/**
* 文件上传工具类
*
* @author ruoyi
*/
public class FileUploadUtils
{
/**
* 默认大小 50M
*/
public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;
/**
* 默认的文件名最大长度 100
*/
public static final int DEFAULT_FILE_NAME_LENGTH = 100;
/**
* 默认上传的原创不易,完成人机校验,阅读全文