<script type="text/javascript">
$(function () {
$('#uploadSubmit').click(function () {
var file = $('#file')[0].files[0];
var fd = new FormData();
fd.append('file', file);
$.ajax({
url: bathpath + '/common/imageUpload' ,
type: 'post',
data: fd,
//dataType:'json',
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data);
if(data.status){
console.log('upload success');
}else{
console.log(data.message);
}
},
error: function (data) {
console.log(data.status);
}
});
});
})
</script>
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
// 保存图片
@POST
@Path("/imageUpload")
@Consumes("multipart/form-data")
public ReturnVO uploadImage(@Context HttpServletRequest request) {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator fileIterator;
String filename = null;
byte[] content = null;
List<String> list = new ArrayList<String>();
try {
fileIterator = upload.getItemIterator(request);
while (fileIterator.hasNext()) {
FileItemStream item = fileIterator.next();
if (item.getFieldName().indexOf("imageUp")>-1) {
content = IOUtils.toByteArray(item.openStream());
filename = System.currentTimeMillis()+"_"+item.getName();
list.add(filename);
filename = path +"images/"+ filename;
FileUtils.writeByteArrayToFile(new File(filename), content);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return new ReturnVO(true,list.toString());
}