標籤:
http上傳檔案方法,使用post方式上傳檔案會因為檔案的編碼問題而存在中文亂碼的問題,通過方法 codeString() 來獲得編碼格式,在自訂的 CustomFilePart() 中得到對應的格式,從而保證格式的一致性,不出現亂碼。
private void httpUpload(String url, String filepath, EssFileServer essFileServer) {File targetFile = new File(filepath);//判斷檔案的編碼格式final String code = codeString(filepath);PostMethod filePost = new PostMethod(url){public String getRequestCharSet() {return code;}};try {Part[] parts = new Part[]{ new CustomFilePart(targetFile.getName() , targetFile) };filePost.setRequestEntity(new MultipartRequestEntity(parts ,filePost.getParams()));HttpClient client = new HttpClient();// 設定http伺服器的登陸使用者名稱和密碼UsernamePasswordCredentials creds = new UsernamePasswordCredentials( essFileServer.getUsername(), essFileServer.getPsw());client.getState().setCredentials(AuthScope.ANY, creds);// 設定逾時時間client.getHttpConnectionManager().getParams().setConnectionTimeout(10000); client.executeMethod(filePost);} catch (Exception e) {e.printStackTrace();} finally {filePost.releaseConnection();}}
CustomFilePart.java
public class CustomFilePart extends FilePart {private String code;public CustomFilePart(String filename, File file) throws FileNotFoundException { super(filename, file);code = HttpClientManager.codeString(file.toString());} protected void sendDispositionHeader(OutputStream out) throws IOException { super.sendDispositionHeader(out); String filename = getSource().getFileName(); if (filename != null) { out.write(EncodingUtil.getAsciiBytes(FILE_NAME)); out.write(QUOTE_BYTES); out.write(EncodingUtil.getBytes(filename, code)); out.write(QUOTE_BYTES); } } }
codeString() 判斷編碼格式的方法,在網上找的,也就懶得改了
/** * 判斷檔案的編碼格式 * @param fileName :file * @return 檔案編碼格式 */public static String codeString(String fileName) {int p = 0;String code = "";BufferedInputStream bin = null;try {bin = new BufferedInputStream(new FileInputStream(fileName));p = (bin.read() << 8) + bin.read();code = null;} catch (Exception e) {e.printStackTrace();} finally {if(null != bin) {try {bin.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}switch (p) {case 0xefbb:code = "UTF-8";break;case 0xfffe:code = "Unicode";break;case 0xfeff:code = "UTF-16BE";break;default:code = "GBK";}}return code;}
這樣就能解決上傳檔案中文亂碼的問題
使用http下載檔案時會出現有空格而無法下載的情況,解決辦法對空格進行轉譯
if(path != null && path.contains(" ")) {path = path.replaceAll(" ", "%20");}
筆記,隨時更新
http上傳下載中遇到的問題