向服务器上 上传图片

时间:2021-12-13 12:17:30

**1.首先配置tomcat服务器上的web.xml(readOnly=false)
2.在服务器上创建一个文件目录(用来存放)
3.导入相关依赖的jar包(jersey json)
4.ajax异步提交**

一:明确资源服务器地址

public class Constant {


public static final String RESOURCEURL="http://192.168.237.129";


}
二:在资源服务器上确定文件路径(创建文件夹)
这里举例:*upImages*
三:配置所上传的最大文件大小,在springmvc配置文件中
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576"></property>
</bean>

<form id="jvForm" action="add!!!" method="post" enctype="multipart/form-data">

<td width="80%" class="pn-fcontent">
<img width="100" height="100" id="allUrl"/>
<input id="imgUrl" name="imgUrl" type="hidden" value=""></input>
<input id="f" name="fileName" type="file" />
</td>

</from>
<script type="text/javascript">
$(function(){
$("#f").change(function(){

$("#jvForm").ajaxSubmit({
url:"URL",//默认是form action
type:"post",
dataType:"json",
success:function(data){
$("#imgUrl").val(data.path);
$("#allUrl").attr("src",data.url);

}
});
});
});
</script>
</body>
</html>


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.apache.commons.io.FilenameUtils;
import org.json.simple.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.classroom.util.Constant;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;

@Controller
public class FileUploadController {

@RequestMapping("/URL")
@ResponseBody
public String fileUpload(MultipartFile fileName){
JSONObject json = new JSONObject();
StringBuilder pathName =new StringBuilder("upImages/");
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssSSS");
pathName.append(sdf.format(new Date()));
for(int i=0;i<4;i++){
Random random=new Random();
pathName.append(random.nextInt(10));
}
pathName.append("."+FilenameUtils.getExtension(fileName.getOriginalFilename()));

json.put("path", pathName.toString());
pathName.insert(0, Constant.RESOURCEURL+"/");
json.put("url",pathName.toString());

Client client = new Client();
WebResource webResource =client.resource(pathName.toString());
try {
webResource.put(String.class, fileName.getBytes());
} catch (UniformInterfaceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientHandlerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json.toJSONString();

}

}

记录一下 有点乱,…