近日因爲項目要求兼容IE7, 不得不修改上傳圖片的插件(由uploadify改爲ocupload)。幾經周折終於搞定上傳功能,在chrome, ff測試都通過,偏偏在IE7會因爲返回值是json, 會彈出下載框。(本機只有原生IE7, 未能測試IE8是否有該問題, 據說IE9及以上是已經支持json格式的)。當然網上還是有大把的解決方案的,個人測試後覺得最靠譜的還是:ContentType設置爲text/plain。項目使用的是springMVC,具體代碼如下:
package cn.***.saas.util;
import net.sf.json.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import cn.***.saas.constant.ResponseCode;
import cn.***.saas.constant.ResponseStatus;
public class ResponseUtilForIe {
public static final String RESPONSE_BODY = "body";
public static final String RESPONSE_STATUS = "status";
public static final String RESPONSE_ERROR = "error";
public static final String RESPONSE_ERROR_CODE = "code";
public static final String RESPONSE_ERROR_MSG = "msg";
public static ResponseEntity<String> jsonSucceed(Object object, HttpStatus statusCode) {
JSONObject jo = new JSONObject();
Object responseBody = DataUtil.formatApiResponse(object);
jo.accumulate(RESPONSE_BODY, responseBody);
return wrapResponse(ResponseStatus.SUCCEED, jo, statusCode);
}
public static ResponseEntity<String> jsonFailed(String errorMessage, HttpStatus statusCode) {
return jsonFailed(errorMessage, ResponseCode.SERVER_ERROR, statusCode);
}
public static ResponseEntity<String> jsonFailed(Object errorMessage, ResponseCode code, HttpStatus statusCode) {
JSONObject errorObj = new JSONObject();
errorObj.accumulate(RESPONSE_ERROR_CODE, code.getValue());
errorObj.accumulate(RESPONSE_ERROR_MSG, errorMessage);
JSONObject error = new JSONObject();
error.accumulate(RESPONSE_ERROR, errorObj);
JSONObject jo = new JSONObject();
jo.accumulate(RESPONSE_BODY, error);
return wrapResponse(ResponseStatus.FAILED, jo, statusCode);
}
private static ResponseEntity<String> wrapResponse(ResponseStatus status, JSONObject body, HttpStatus statusCode) {
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "text/plain;charset=UTF-8");
if (ResponseStatus.SUCCEED.equals(status)) {
body.accumulate(RESPONSE_STATUS, ResponseStatus.SUCCEED.toString());
} else if (ResponseStatus.FAILED.equals(status)) {
body.accumulate(RESPONSE_STATUS, ResponseStatus.FAILED.toString());
}
return new ResponseEntity<String>(body.toString(), headers, statusCode);
}
}
在上傳圖片的controller方法裏,返回值直接使用方法即可。
此外也有說通過修改註冊表的, 方法是: 在註冊表中添加如下項:
[HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=dword:00080000
[HKEY_CLASSES_ROOT\MIME\Database\Content Type\text/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"encoding"=dword:00080000
或者直接將上述代碼保存爲.reg文件,雙擊執行即可。不過本人未曾試過此方法,因爲對於web項目,不可能要求或者強制用戶都修改註冊表。