SpringMVC的下載功能正常是很簡單,但是因為昨天專案配置了JSON的資料傳輸,導致我的下載功能,一直出錯,能正常執行,但是下載的圖片都是被破壞了,無法檢視,當時糾結了好久,一直不知道問題出在哪裡。
程式
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("download")
public class UploadController {
@RequestMapping("down")
@ResponseBody
public ResponseEntity<byte[]> download(){
String path="E:/temp/";
String filename="31.jpg";
File file = new File(path+filename);
HttpHeaders headers = new HttpHeaders();
String downloadFileName = "default.jpg";
try {
//防止中文亂碼
downloadFileName = new
String(filename.getBytes("UTF-8"),"ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//通知瀏覽器以attachment(下載方式)開啟圖片
headers.setContentDispositionFormData("attachment"
, downloadFileName);
//application/octet-stream 二進位制流資料
headers.setContentType(MediaType
.APPLICATION_OCTET_STREAM);
try {
return new ResponseEntity<byte[]>
(FileUtils.readFileToByteArray(file),headers,HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
複製程式碼
正常上面的程式碼就可以實現SpringMVC的下載功能,不過因為配置JSON的傳輸資料格式,導致下載錯誤,需要配置一下才能正常。
配置
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json
.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<bean id="byteArrayHttpMessageConverter"
class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.web.servlet.mvc
.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list >
<ref bean="mappingJacksonHttpMessageConverter" />
<ref bean="byteArrayHttpMessageConverter" />
</list>
</property>
</bean>
複製程式碼
以上配置即可正常執行。