spring mvc怎么下载图片呢?
有两种方式:
方式一:使用注解@responsebody

@responsebody
@requestmapping(value = "/download",produces="image/jpeg")
public byte[] downloadfile(httpservletrequest request, httpservletresponse response,string contenttype2,boolean isinline)
throws ioexception {
byte[]bytes=fileutils.getbytes4file("d:\\temp\\cc.jpg");
// response.addheader("content-disposition", downloadtype+";filename=\"a.jpg\"");
webservletutil.setdownloadcontentdisposition(isinline, "c.jpg", response);
return bytes;
}
webservletutil.setdownloadcontentdisposition 的实现如下:

/***
* spring mvc下载文件设置的content-disposition
* @param isinline
* @param filename
* @return
*/
public static string getcontentdisposition(boolean isinline,string filename){
string downloadtype=null;
if(isinline){
downloadtype=constant2.content_disposition_inline;
}else{
downloadtype=constant2.content_disposition_attachment;
}
if(valuewidget.isnullorempty(filename)){
filename="name_not_specified";
string format=downloadtype+";filename=\""+filename+"\"";
return format;
/***
* 下载文件(或内联显示)时设置content-disposition
* @param response
public static void setdownloadcontentdisposition(boolean isinline,string filename, httpservletresponse response){
response.addheader(constant2.content_disposition, webservletutil.getcontentdisposition(isinline, filename));
注意:(1)一定要通过@requestmapping注解的produces 设置response 的content type;
(2)设置应答头时要使用addheader,而不是setheader
方式二:使用responseentity

@requestmapping(value = "/download3")
public responseentity<byte[]> download() throws ioexception {
httpheaders headers = new httpheaders();
headers.setcontenttype(mediatype.image_jpeg);
// headers.setcontentdispositionformdata("inline", "dict.jpg");//attachment
headers.set(constant2.content_disposition,webservletutil.getcontentdisposition(true, "dict.jpg"));
return new responseentity<byte[]>(fileutils.getbytes4file("d:\\temp\\cc.jpg"),
headers, httpstatus.created);

* favicon.ico
* @throws ioexception
@requestmapping(value = "/favicon.ico")
public responseentity<byte[]> faviconico(httpservletrequest request) throws ioexception {
headers.setcontenttype(mediatype.image_png);
string faviconiconame="sms-4.ico";
headers.set(constant2.content_disposition,webservletutil.getcontentdisposition(true, faviconiconame));
///home/whuang/software/apache-tomcat-7.0.53/webapps/root/
string webapppath=null;
if(webservletutil.islocalip(request)){//服务器在本机(访问ip为127或localhost)
webapppath=webservletutil.getrealpath(request);
webapppath=dictionaryparam.get(constant2.dictionary_group_global_setting, "web-inf_loc");
return new responseentity<byte[]>(fileutils.getbytes4file(
webapppath
+"web-inf/static/img/"+faviconiconame),
注意:不要使用headers.setcontentdispositionformdata 来设置content-disposition