1.js进行图片预览
使用input标签来选择图片,使用FileReader读取图片并转成base64
编码,然后发送给服务器。
class="html/js" name="code">
<html>
<body>
<img id="image" src="" />
<br/>
<input type="file" onchange="selectImage(this);"/>
<br/>
<input type="button" onclick="uploadImage();" value="提交"/>
<script>
var image = '';
function selectImage(file){
if(!file.files || !file.files[0]){
return;
}
var reader = new FileReader();
reader.onload = function(evt){
document.getElementById('image').src = evt.target.result;
image = evt.target.result;
}
reader.readAsDataURL(file.files[0]);
}
function uploadImage(){
$.ajax({
type:'POST',
url: 'ajax/uploadimage',
data: {image: image},
async: false,
dataType: 'json',
success: function(data){
if(data.success){
alert('上传成功');
}else{
alert('上传失败');
}
},
error: function(err){
alert('网络故障');
}
});
}
</script>
<script src="jquery-1.11.1.min.js"></script>
</body>
</html>
2.服务器接收数据,然后写到磁盘
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sun.misc.BASE64Decoder;
/**
* 上传图片。
*/
public class UploadImageAjax extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
String image = req.getParameter("image");
// 只允许jpg
String header = "data:image/jpeg;base64,";
if(image.indexOf(header) != 0){
resp.getWriter().print(wrapJSON(false));
return;
}
// 去掉头部
image = image.substring(header.length());
// 写入磁盘
boolean success = false;
BASE64Decoder decoder = new BASE64Decoder();
try{
byte[] decodedBytes = decoder.decodeBuffer(image);
String imgFilePath = "D://uploadimage.jpg";
FileOutputStream out = new FileOutputStream(imgFilePath);
out.write(decodedBytes);
out.close();
success = true;
}catch(Exception e){
success = false;
e.printStackTrace();
}
resp.getWriter().print(wrapJSON(success));
}
private String wrapJSON(boolean success){
return "{\"success\":" + success + "}";
}
}
3.配置文件web.xml
<web-app>
<servlet>
<servlet-name>UploadImage</servlet-name>
<servlet-class>UploadImageAjax</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadImage</servlet-name>
<url-pattern>/ajax/uploadimage</url-pattern>
</servlet-mapping>
</web-app>
4.需要注意的地方
需要jquery的支持:jquery-1.11.1.min.js
需要servlet的支持:servlet-api.jar
需要Base64解码支持:sun.misc.BASE64Decoder。引入这个包eclipse可能会报错,请按照http://blog.csdn.net/hurryjiang/article/details/6958146进行处理。
- UploadImage.rar (218.5 KB)
- 描述: 上传图片的project
- 下载次数: 0