1.表单
<form action="" name="myForm" id="myForm" method="post" enctype="multipart/form-data">
<a name="uploadImgs" id="uploadImgs"></a>
<p><label><samp>*</samp>上传商品图片(90x150尺寸):</label><span id="uploadImgTip1" class="orange">注:该尺寸图片必须为90x150。</span></p>
<p><label></label>
<img id='imgsImgSrc' src='' height="100" width="100" />
<input type='file' id='imgsFile' name='imgsFile' class="file" οnchange='submitImgSize1Upload()' /><span class="pos" id="imgSize1FileSpan">请上传图片的大小不超过3MB</span>
<input type='hidden' id='imgs' name='imgs' value='' reg="^.+$" tip="亲!您忘记上传图片了。" />
</p>
</form>
2.jQuery实现表单提交上传回显图片
function submitUpload(){
var option = {
url:path+"/upload/uploadPic.do",//上传的url
dataType:"text",//回调值的数据类型
success:function(responseText){
//{"realPath":"http://...", "relativePath":"/upload/.."}
var jsonObj = $.parseJSON(responseText);
$("#imgsImgSrc").attr("src", jsonObj.realPath);
$("#imgs").val(jsonObj.relativePath);
$("#lastRealPath").val(jsonObj.realPath);
},
error:function(){
alert("系统错误");
}
}
//使用ajax方式提交表单,上传文件
$("#form111").ajaxSubmit(option);
}
3.设置服务器路径
新建路径文件ecps_prop.properties :upload_file_path=http://localhost:8083/ecps-file
读取文件:
public class ECPSUtils {
public static String readProp(String key){
String value = null;
InputStream in = ECPSUtils.class.getClassLoader().getResourceAsStream("ecps_prop.properties");
Properties prop = new Properties();
try {
prop.load(in);
value = prop.getProperty(key);
} catch (IOException e) {
e.printStackTrace();
}
return value;
}
}
4.controller类
@RequestMapping("/upload")
public class EbUploadController {
@RequestMapping("/uploadPic.do")
public void uploadPic(HttpServletRequest request, PrintWriter out, String lastRealPath) throws IOException{
//强制转换request
MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
//从表单获得文件
//获得文件类型input的name
Iterator<String> iter = mr.getFileNames();
String inputName = iter.next();
//获得文件
MultipartFile mf = mr.getFile(inputName);
byte[] mfs = mf.getBytes();
//定义上传后的文件名字
String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
Random random = new Random();
for(int i = 0; i < 3; i++){
fileName = fileName + random.nextInt(10);
}
//获得后缀名
String oriFileName = mf.getOriginalFilename();
String suffix = oriFileName.substring(oriFileName.lastIndexOf("."));
//要上传文件的绝对路径
String realPath = ECPSUtils.readProp("upload_file_path")+"/upload/"+fileName + suffix;
String relativePath = "/upload/"+fileName + suffix;
//由于我们需要在不同主机上上传不能直接通过流的方式写文件
//创建Jersey客户端
Client client = Client.create();
//判断是不是第一次上传
if(StringUtils.isNotBlank(lastRealPath)){
WebResource wr = client.resource(lastRealPath);
wr.delete();
}
//指定要上传的具体的地址,参数就是要上传的图片的绝对路径
WebResource wr = client.resource(realPath);
//文件的上传到文件主机上
wr.put(mfs);
//使用json对象把绝对路径和相对路径写回去
JSONObject jo = new JSONObject();
jo.accumulate("realPath", realPath);
jo.accumulate("relativePath", relativePath);
//{"realPath":"http://...", "relativePath":"/upload/.."}
String result = jo.toString();
out.write(result);
}